写了一个暴力破解的,没想到用了4ms,是最快那部分的。。。效率是O(m*n)
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
for(int i = 0;i<haystack.size();i++){
if((i+needle.size())>haystack.size()) return -1;
if(haystack[i] == needle[0]){
int j ;
for(j = 1;j<needle.size();j++){
if(needle[j] != haystack[i+j]) break;
}
if(j == needle.size()) return i;
}
}
return -1;
}
然后我又写了一个据说是最快的字符串匹配算法,sunday算法,然后更慢了,估计是我写的有问题。
private:
int sunday(char c,string needle){
int index = 0;
for(int i = needle.size() - 1;i>=0; i--){
if(needle[i] == c){
return index+1;
}
index++;
}
return needle.size() + 1;
}
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
for(int i = 0;i<haystack.size();){
if((i+needle.size())>haystack.size()) return -1;
if(haystack[i] == needle[0]){
int j ;
for(j = 1;j<needle.size();j++){
if(needle[j] != haystack[i+j]) break;
}
if(j == needle.size()) return i;
i++;
}else{
char c = haystack[i+needle.size()];
int index = sunday(c,needle);
i +=index;
}
}
return -1;
}
不过思路是按照sunday算法来的,可能在字符串查找那里用树之类的会更快吧。