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个位置之间的字符串,‘含头不含尾’)。
class Solution {
public:
int strStr(string haystack, string needle)
{
int num1=haystack.length();
int num2=needle.length();
if(num2==0)
return 0;
if(num1==0||num1<num2)
return -1;
for(int i=0;i<=num1-num2;i++)
{
if(haystack.substr(i,num2)==needle)
return i;
}
return -1;
}
};
KMP先放放。。
寒假也太欢乐了。
导致排名都降了,难受。
solution 3.KMP方法
next数组的求法:
- 首先next[0]=0;我看到有博主是将next[0]=-1,next[1]=0;这个应该是不同的计数方法,不影响匹配。i表示最前面的,j会移动。
- 对每一个j的next进行求解,needle[j]==needle[i]的话,next[j]=next[i]+1;
- 如果不相等且next[i]!=0,比较needle[j]与needle[next[i]]是否相等:若相等,next[j]=next[next[i]]+1;else重复3,直至next[next…[i]]=0;
solution 4
using the function “find”
int StrStr(string haystack, string needle) {
return haystack.find(needle);
}
不知道为什么KMP对我来说这么难,我先放几天再说,代码一直有问题,还是自己逻辑不对,整了一天也没做出来,啊,人生啊。