题目链接:https://leetcode.com/problems/implement-strstr/description/
以下列舉暴力法和KMP
//time: O(n*m) ,space 1
//最简单的方法,每一个枚举一遍
//注意为空,长度不符合 特殊情况,输入[1,2,3],要求[1,2,3,4]
//注意需要枚举的长度
//更快的方法:rabin card , KMP
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() == 0 && needle.size() != 0 ) return -1;
if(haystack.size() == 0 && needle.size() == 0 ) return 0;
if(haystack.size() < needle.size()) return -1;
int curIdx ;
for(int i = 0 ; i <= haystack.size() - needle.size() ; i++){
curIdx = 0 ;
for(; curIdx < needle.size() ; curIdx++){
if( haystack[i + curIdx] != needle[curIdx])
{break ;}
}
if(curIdx == needle.size())
{return i;}
}
return -1 ;
}
int strStr(string haystack, string needle){
int n=haystack.length(), m = needle.length();
if(m>n) return -1;
if(m==0) return 0;
for(int i=0;i<n-m;i++){
string sub = haystack.substr(i, m);
if(sub == needle) return i;
}
return -1;
}
O(n*m)
haystack = “”
needle = “”
?
haystack = “”
needle = “abc”
?
KMP有bug版本
int kmp_search(string haystack, string needle){
int n = haystack.length(), m = needle.length();
if(m>n) return -1;
if(m==0) return 0;
int i=0, j=-1;
vector<int> prefix(m+1, 0);
prefix[0] = -1; //“a p p l a p t t c a p”
//a p p l a p p l
-1 0 0 0 1 2 3
i 0 1 2 3 4 5 6 7
j -1 0 0 0 1 2 3 4
while(i<m){
while(j>=0 && needle[i]!=needle[j]) j = prefix[j];
i++, j++;
prefix[i] = j;
}
i=0, j=0;
while(i<n){
while(j>=0 && haystack[i]!=needle[j]) j = prefix[j];
i++, j++;
if(j==m) {
return i-j;
}
}
return -1;
}
“a p p l a p p l”
-1 0 0 0 0 1 2 3
“a p p l a p t t c a p”
a p p l a p p l
a p p l a p p l
class Solution {
// a p p l a p p l
// old_i x 0 1 2 3 4 5 6 (進行++之前)
// old_j x -1 - 1 -1 -1 0 1 2 (進行++之前)
// i 0 1 2 3 4 5 6 7
// j -1 0 0 0 0 1 2 3
public:
int kmp_search(string a, string b){
int n = a.length(), m = b.length();
int i=0,j=-1;
if(m>n) return -1;
if(m==0) return 0;
vector<int> prefix(b.length()+1,0);
prefix[0] = -1;
while(i<m){
while(j>=0 && b[i]!=b[j]) j = prefix[j];
i++;
j++;
prefix[i] = j;
}
i=0, j =0;
while(i<n){
while(j>=0 && a[i] != b[j]) j = prefix[j];
i++;j++;
if(j == m) return i-j;
}
return -1;
}
int strStr(string haystack, string needle) {
return kmp_search(haystack, needle);
}
};