参考:
【soso字幕】汪都能听懂的KMP字符串匹配算法【双语字幕】
KMP,Sunday等高级算法在处理长文本时候有优势,在字符串较短时候因为需要预处理和额外空间,效率反而没有BF算法高
比如leetcode #28,滑动窗口居然比kmp快得多:
kmp实现:
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals("")) return 0;
if (haystack.equals("")) return -1;
char[] hstr = haystack.toCharArray();
char[] nstr = needle.toCharArray();
int [] next = getnext(nstr);
//匹配
int m = 0, n = 0;
while (m < hstr.length && n < nstr.length) {
if (hstr[m] == nstr[n]) {
//单次匹配成功
m++;
n++;
} else if (hstr[m] != nstr[n] && n > 0) {
//单次匹配失败但n不为0
n = next[n - 1];
continue;
} else if (hstr[m] != nstr[n] && n == 0) {
//单次匹配失败且n=0
m++;
}
}
return n == nstr.length? m - n: -1;
}
public int[] getnext(char[] str){
//构建next数组
int []next = new int[str.length];
int i = 1;
int j = 0;
next[0] = 0;
while (i < str.length) {
if (str[i] == str[j]) {
//i与j相同时
next[i] = j + 1;
i++;
j++;
} else {
//i与j不同时,以j是否为0判断j是否移动
if (j == 0) {
next[i] = j;
i++;
}
if (j != 0) {
j = next[j - 1];
//再比较j与i
continue;
}
}
}
return next;
}
}
滑动窗口实现:
class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();
for (int start = 0; start < n - L + 1; ++start) {
if (haystack.substring(start, start + L).equals(needle)) {
return start;
}
}
return -1;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。