1.暴力 遍历
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
if(haystack.empty())
return -1;
if(haystack.size()<needle.size())
return -1;
int i=0;
int j;
for(;i<=haystack.size()-needle.size();i++){
j=0;
for(;j<needle.size();j++){
if(needle[j]!=haystack[i+j]){
break;
}
}
if(j==needle.size()){
break;
}
}
if(i<=haystack.size()-needle.size() && j==needle.size()){
return i;
}
else{
return -1;
}
}
};
2.KMP算法:字符串匹配
next数组可以理解为状态的跳转:
(1)状态i左侧的字符全部匹配成功,当状态i右侧第一个字符匹配不成功时,跳转到状态next[i]。
(2)因为状态i左侧串的子串与状态next[i]左侧串相同(即:状态i左侧串的长度为next[i]的前缀子串和后缀子串相同)
//求解next数组
int i=0,j=-1;
vector<int> next(needle.size()+1);
next[0]=-1;
while(i<needle.size()-1){
if(j==-1 || needle[i]==needle[j]){
i++;j++;
next[i]=j;
}
else
j=next[j];
}
next[0]=-1是为了字符串匹配时的计算方便。
字符串匹配时的情况:
(1)text[i]与pattern[0]匹配不成功,则下一个比较text[i+1]与pattern[0];
(2)j>0,text[i]与pattern[j]匹配不成功,则下一个比较text[i]与pattern[next[j]];
(3)j>0,text[i]与pattern[j]匹配成功,则下一个比较text[i+1]与pattern[j+1];
完整代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
if(haystack.empty())
return -1;
if(haystack.size()<needle.size())
return -1;
//求解next数组
int i=0,j=-1;
vector<int> next(needle.size()+1);
next[0]=-1;
while(i<needle.size()-1){
if(j==-1 || needle[i]==needle[j]){
i++;j++;
next[i]=j;
}
else
j=next[j];
}
//字符串匹配
i=0;j=0;
while(i<haystack.size()&&j<needle.size()){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
j=next[j];
if(j==-1){
i++;j++;
}
}
}
if(j>=needle.size())
return i-needle.size();
else
return -1;
}
};