KMP算法——解决字符串匹配问题
eg.文本串aabaabaaf 长度m
模式串aabaaf 长度n
时间复杂度O(m*n)
前缀表:
前缀:包括首字母,不包括尾字符的所有子串
后缀:包括尾字母,不包括首字符的所有子串
前缀表是用来回退的,它记录了模式串与主串(文本串)不匹配的时候,模式串应该从哪里开始重新匹配——下标i之前(包括i)的字符串中,有多大长度的相同前缀后缀
求最长相等前后缀:
第一个字母a 没有相同前后缀:0
aa:1
aab:0
aaba:1
aabaa:2
aabaaf:0
前缀表元素为[0,1,0,1,2,0]
class Solution {
//前缀表(不减一)Java实现
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle.charAt(j) != haystack.charAt(i))
j = next[j - 1];
if (needle.charAt(j) == haystack.charAt(i))
j++;
if (j == needle.length())
return i - needle.length() + 1;
}
return -1;
}
private void getNext(int[] next, String s) {
int j = 0;
next[0] = 0;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(j) != s.charAt(i))
j = next[j - 1];
if (s.charAt(j) == s.charAt(i))
j++;
next[i] = j;
}
}
}