【题目描述】
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
【思路】采用brute force方法暴力求解,复杂度o(n*m),速度还蛮快的,4ms,采用KMP算法可能会更快一点,但是KMP比较复杂,不适合在面试这种有限的时间内实现。
【代码】
class Solution {
public:
int strStr(string haystack, string needle) {
int len=haystack.length();
int len2=needle.length();
int cnt=0;
int i,j;
if(len2==0||(len==0&&len2==0)) return 0;
if(len==0&&len2!=0) return -1;
for(i=0;i<=len-len2;i++){
cnt=0;
for(j=0;j<len2;j++){
if(needle[cnt]!=haystack[i+j]){
break;
}
else cnt++;
if(cnt==len2) return i;
}
}
return -1;
}
};