一,字符串匹配的目的
在目标串中找到与模式串相同的子串,如果在目标串中存在这样的子串,则返回子串的位置,没有这样的子串返回-1。
二,KMP字符串匹配算法
基本思想:
利用模式串中的部分信息,首先使用一个数组(next)保存模式串中的每个字符前面最多有多少个字符与从头开始的字符串是相同的。
算法实现:
void getNext(string &t, vector<int> &next){
next[0] = -1;
next[1] = 0;
for(int i = 2; i < t.size(); i ++){
int k = next[i - 1];
if(t[i - 1] == t[k]){
next[i] = next[i - 1] + 1;
} else if (t[i - 1] == t[0]){
next[i] = 1;
} else {
next[i] = 0;
}
}
}
int KMPIndex(string &s, string &t){
int i = 0, j = 0;
vector<int> next(t.size());
getNext(t, next);
while(i < s.size() && j < t.size()){
if(j == -1 || s[i] == t[j]){
i ++;
j ++;
} else {
j = next[j];
}
}
if(j >= t.size()){
return i - t.size();
} else {
return -1;
}
}