Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
首先要搞懂strStr()是啥,strStr()是判断一个字符串是否为另一个字符串的子串。最简单的算法是遍历(m-n)*n次,代码如下:
<span style="color:#333333;">int hay=0,nee=0;
int h=haystack.size();int n=needle.size();
</span><span style="color:#ff0000;"> while(hay<(h-n))</span><span style="color:#333333;">{
if(haystack[hay]==needle[0]){
int thay=hay,tnee=0;
while(tnee<n&&thay<h){
if(needle[tnee]==haystack[thay]){ tnee++;thay++;}
else break;
}
if(tnee==(n)) return hay;
hay++;
}else{
hay++;
}
}
return -1;</span>
要注意红字部分,不需要遍历完haystack字符串,因为在(h-n)这个位置如果还不存在子串,就不用再判断后面的部分了,因为字符串的大小就不满足关系了。我看到讨论说有KMP算法,我有空在看下吧。