kmp算法的java实现
kmp算法,java代码。先看代码,有空再来细说。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TestString { private String testStr = "ACHHEEDHEYBGREATEBALLHEYUSHIGEDAHAORENALORENZOYESHIHAORENHEYU"; // 朴素的匹配算法 public int bf(String s) { int i = 0; int j = 0; while (i < testStr.length() && j < s.length()) { if (testStr.charAt(i) == s.charAt(j)) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j == s.length()) { return i - j; } else { return -1; } } // KMP算法 public int kmp(String s) { int i = 0; int j = 0; int[] next = new int[s.length()]; next = preNext(s); while (i < testStr.length() && j < s.length()) { if (j == -1 || testStr.charAt(i) == s.charAt(j)) { i++; j++; } else { j = next[j]; } } if (j == s.length()) { return i - j; } else { return -1; } } // 前缀函数 public int[] preNext(String s) { int[] next = new int[s.length()]; int i, j, temp; for (i = 0; i < s.length(); i++) { if (i == 0) { next[i] = -1; } else if (i == 1) { next[i] = 0; } else { temp = i - 1; for (j = temp; j > 0; j--) { if (s.charAt(i) == s.charAt(j)) { next[i] = j; break; } } if (j == 0) next[i] = 0; } } return next; } public static void main(String[] args) { TestString ts = new TestString(); System.out.println(" bf: " + ts.bf("HEYU")); System.out.println("kmp: " + ts.kmp("HEYU")); } }