题意:
implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题解:
直接暴力解法,O(m*n)。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
const int N = haystack.size()-needle.size()+1;
for(int i=0;i<N;++i){
int j = i;
int k = 0;
while(j<haystack.size()&&k<needle.size()&&haystack[j]==needle[k]){
j++;
k++;
}
if(k == needle.size()) return i;
}
return -1;
}
};