如何确定子串在主串的位置?
• 暴力匹配算法
//暴力查找子串位置
int index(string s, string t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s[i] == t[j]) {
i++;
j++;
} else {
i = i - ( j-1 );
j = 0;
}
}
if (j >= t.length()) return i - t.length();
return 0;
}
• KMP算法
1. next数组定义:当主串与模式串的某一位字符不匹配时,模式串要回退的位置
2. next[ j ]:其值 = 第 j 位字符串前面 j-1 位字符串组成的子串的前后缀最大重合字符长度+1
-
如何手算next数组?
-
next数组思路
1. next[ j+1 ]的最大值为next[ j ]+1
2. 如果Pk1 != Pj,那么next[ j+1 ]可能的次大值为next[ next[j] ] + 1
- next数组代码实现
int getNext(char ch[], int len, int next[]) {//len为串ch的长度
next[1] = 0;
int i = 1, j = 0;
while (i < len) {
if (j == 0 || ch[i] == ch[j]) next[++i] = ++j;
else j = next[j];
}
}
• 注:next[ 0 ]可以用来存储长度,一个字节八位,最大256
- KMP全部过程代码
void getNext(const string &str, int *next, int len) {
next[1] = 0;
int i = 1, j = 0;
while (i < len-1) {
if (j == 0 || str[i] == str[j]) {
++i;
++j;
next[i] = str[i]==str[j]?next[j]:j;
}
else j = next[j];
}
}
int strStr(string haystack, string needle) {
if (needle.length()==0) return 0;
needle = " " + needle;
haystack = " " + haystack;
int len1 = haystack.length();
int len2 = needle.length();
int *next = new int[len2]();
getNext(needle,next,len2);
int i=1,j=1;
while (i < len1 && j < len2) {
if (j==0 || haystack[i] == needle[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j>len2-1) return i-len2;
return -1;
}