1、蛮力匹配:
版本1:
版本2:
效率分析:
- 最好情况:O(m)
- 最坏情况:O(m * n)
2、KMP算法
- 算法
-
next表实例
-
-
next表构造(仅取决于模式串)
哨兵 next[0]=−1;next[0] = -1;next[0]=−1;
next[j+1]<=next[j]+1next[j + 1] <= next[j] + 1next[j+1]<=next[j]+1
当且仅当P[j]==P[next[j]]P[j] == P[next[j]]P[j]==P[next[j]]时取等号
当P[j]!=P[next[j]]P[j] != P[next[j]]P[j]!=P[next[j]],有
-
复杂度分析
最坏情况:O(n)O(n)O(n)
改进
LeetCode 28
int* buildNext(string str)
{
int m = str.size(), j = 0;
int *N = new int[m];
int t = N[0] = -1;
while (j < m - 1) {
if (0 > t || str[j] == str[t]) {
N[++j] = ++t;
}
else
t = N[t];
}
return N;
}
int match(string str1, string str2) {
int *next = buildNext(str1);
int n = str2.size(), i = 0;
int m = str1.size();
int j = 0;
while (i < n) {
if (0 > j || str2[i] == str1[j]) {
i++;
j++;
}
else
j = next[j];
if(j == m)
{
delete[] next;
return i - j;
}
}
return -1;
}
int strStr(string haystack, string needle) {
if (haystack.empty() && needle.empty())
return 0;
if (needle.size() == 0)
return 0;
if (haystack.size() < needle.size())
return -1;
return match(needle, haystack);
}
参考:
https://zhuanlan.zhihu.com/p/34905259
https://leetcode.com/problems/word-break/description/
http://wiki.jikexueyuan.com/project/kmp-algorithm/define.html
https://leetcode.com/problems/implement-strstr/description/