题目:
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(needle.length()==0) return 0;
int m=haystack.length(),n=needle.length();
//暴力破解法:
for(int i=0;i<m;i++){
int k=0;
//从某个位置i开始,连续k个值在haystack和needle里是相同的
while(k<n&&haystack[i+k]==needle[k]){
k++;
}
//说明needle是haystack的一部分
if(k==n) return i;
}
return -1;
}
};