字符串匹配的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; } }
相关文章推荐
- C语言实现字符串匹配KMP算法
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法、Boyer-Moore算法
- Luogu 3375 【模板】KMP字符串匹配(KMP算法)
- 极其通熟易懂——字符串匹配的KMP算法
- 字符串匹配的KMP算法彻底理解
- 字符串匹配算法(二)-KMP算法
- 字符串匹配的KMP算法
- 字符串匹配,KMP算法
- 字符串匹配的KMP算法
- 浅谈字符串匹配的KMP算法
- 数据结构之字符串匹配算法(BF算法和KMP算法)
- 字符串匹配问题——KMP算法实现
- 字符串匹配KMP算法
- 字符串匹配 KMP算法
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法
- kmp算法(用来处理字符串匹配)