朴素算法
- 该算法的思路是设置两个i, j指针,依次遍历不等则回溯
- 算法思路简单但时间复杂度高达o(length1 * length2)
算法比较简单,因此直接看实现:
int Index(string S, string T) {
int len1 = S.length();
int len2 = T.length();
int i = 0, j = 0;
while (i != len1 && j != len2) {
if (S[i] == T[j]) {
i++;
j++;
}
else {
j = 0;
i = i - j + 1;
}
}
if (j == len2)
return i - j + 1;
return -1;
}
接下来看KMP的实现思路:
next函数:
void get_next(string T, int **next) {
int len = T.length();
int i = 1, j = 0;
(*next)[0] = 0;
while (i < len) {
if (j == 0 || T[i - 1] == T[j - 1]) {
i++;
j++;
(*next)[i - 1] = j;
}
else {
j = (*next)[j - 1];
}
}
}
KMP函数:
int Index_KMP(string S, string T, int *next) {
int len1 = S.length();
int len2 = T.length();
int i = 1, j = 1;
while(i <= len1 && j <= len2) {
if (j == 0 || S[i - 1] == T[j - 1]) {
i++;
j++;
}
else {
j = next[j - 1];
}
}
if (j - 1 == len2)
return i - j + 1;
return 0;
}
改进后的index函数:
void get_nextval(string T, int **next) {
int len = T.length();
int i = 1, j = 0;
(*next)[0] = 0;
while (i < len) {
if (j == 0 || T[i - 1] == T[j - 1]) {
i++;
j++;
(*next)[i - 1] = j;
if (T[i - 1] == T[j - 1])
(*next)[i - 1] = (*next)[j - 1];
}
else {
j = (*next)[j - 1];
}
}
}