题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
寻找needle在haystack中出现的位置。
一个个比较呗。
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack==""||haystack.size()<needle.size()){
if(needle=="")
return 0;
return -1;
}
int i,j;
for(i=0,j=0;i<haystack.size()&&j<needle.size();){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
i-=j-1;
j=0;
if((haystack.size()-i)<needle.size())
break;
}
}
return j!=needle.size()?-1:(i-j);//j如果不等于<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">needle.size(),表示上面的循环中没有匹配成功,因为如果匹配成功,那么j应该指向needle末端的下一位置</span>
}
};