您的位置:首页 > 其它

字符串匹配的KMP算法

2017-12-20 21:02 281 查看
我一直感觉KMP算法好难好难哦,很久很久之前我就看到这个算法了,看了好久都没看懂,今天突然心血来潮又想回顾一下这个难难的算法,然而,看了五六个小时,依然晕乎乎,似懂非懂。不过我发现有几篇关于KMP的文章确实写的不错,值得转载。

点击查看原文

//查找第一个匹配的子串的位置

public class KMP {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String str = scanner.next();
String t = scanner.next();
System.out.println(indexKMP(str,t));
}
}

private static int indexKMP(String str, String tr) {
char s[] = str.toCharArray();
char t[] = tr.toCharArray();
int next[];
next = getNext(t);
int k = -1;
for(int  i = 0; i < s.length; i++){
while (k > -1 && t[k+1] != s[i]){
k = next[k];//往前回溯
}
if (t[k+1] ==  s[i]){
k++;
}
if(k == t.length - 1){//到了最末端
//k = -1;重新初始化,寻找下一个
//i = i - t.length + 1;i定位到当前该位置,外层循环i++可以寻找下一个
//如果只找第一个,则注释上面的两行。
return i - t.length+1;
}
}
return -1;
}

private static int[] getNext(char[] chars) {
int [] next = new int[chars.length];
int j = 0;
int k = -1;
next[0] = -1;
while (j < chars.length - 1){
if(k == -1 ||chars[j] == chars[k]){
next[++j] = ++k;
}else {
k = next[k];
}
}
return next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: