28. Implement strStr()

Description:
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
when needle is an empty string,we will return 0.

Solution 1:
思路是首先在haystack中的下標最大隻能到num1-num2,所以只需比對這之前的,然後i是一個記位器的功能,j是用來控制兩個string中的位置的

int strStr(string haystack, string needle)
{
	int num1 = haystack.length();
	int num2 = needle.length();
	for (int i = 0; i < num1-num2+1; i++)
	{
		int j = 0;
		while (j < num2&&haystack[i + j] == needle[j])
			j++;
		if (j == num2)
			return i;
	}
	return -1;
};

Solution 2:
思路是利用substr()這個函數自帶的字符串匹配功能去做。

substr(startIndex,lenth): 第二個參數是截取字符串的長度(從起始點截取某個長度的字符串);
substring(startIndex, endIndex): 第二個參數是截取字符串最終的下標 (截取2個位置之間的字符串,‘含頭不含尾’)。

int strStr(string haystack, string needle)
    {
        int num1=haystack.length();
        int num2=needle.length();
        int j=0;
        if(num2==0)
            return 0;
        for(int i=0;i<num1&&j<num2;i++)
        {
          if(haystack.substr(i,num2)==needle)
             return i;      
        }
        return -1;
    }

KMP先放放。。
寒假也太歡樂了。
導致排名都降了,難受。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章