KMP算法学习笔记
字符串匹配的KMP算法(这篇写的十分清楚)
其中next数组实质上就是“前缀”和“后缀”的最长共有元素的长度。
具体实现是这样的:
以"ABCDABD"为例:
s表示字符串"ABCDABD"
next[]数组表示部分匹配表
i表示当前遍历字符串的下标
j表示共有元素的最长长度,初始值为0
当i = 0
“A”的前缀后缀皆为0,next[ 0 ]必定为0,j为0
当i = 1,j = 0
所以next[ 1 ] = 0,j = 0;
当i = 2,j = 0
以此类推,每一次的比较都只需要判断s[ j ]和s[ i ]
如果s[ j ] == s[ i ] ,j++
如果j > 0 && s[ j ] != s[ i ],j值回溯 j = next[ j - 1 ]
具体实现代码
int len = s.length();
//先找到next数组
int[] next = new int[len];
for (int i = 1, j = 0; i < len; 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;
}
字符串匹配代码:
写的是LeetCode 214题
class Solution {
public String shortestPalindrome (String s) {
int len = s.length();
//先找到next数组
int[] next = new int[len];
for (int i = 1, j = 0; i < len; 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;
}
int j = 0;
for(int i = len - 1;i >= 0; i--){
while (s.charAt(i) != s.charAt(j) && j > 0){
j -= j- next[j-1];
}
if (s.charAt(i) == s.charAt(j)){
j++;
}
}
return new StringBuilder(s.substring(j)).reverse()+s;
}
}