前缀和后缀

image.png
image.png
image.png

  1. 通过前缀和后缀获得每一个字符前边的所有字符前缀和后缀最大匹配长度

    1. public class KMP {
    2. public static int getIndexOf(String s, String m) {
    3. if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
    4. return -1;
    5. }
    6. char[] str1 = s.toCharArray();
    7. char[] str2 = m.toCharArray();
    8. int i1 = 0;
    9. int i2 = 0;
    10. int[] next = getNextArray(str2);
    11. while (i1 < str1.length && i2 < str2.length) {
    12. if (str1[i1] == str2[i2]) {
    13. i1++;
    14. i2++;
    15. } else if (next[i2] == -1) { // i2 = 0
    16. i1++;
    17. } else {
    18. i2 = next[i2];
    19. }
    20. }
    21. return i2 == str2.length ? i1 - i2 : -1;
    22. }
    23. public static int[] getNextArray(char[] ms) {
    24. if (ms.length == 1) {
    25. return new int[] { -1 };
    26. }
    27. int[] next = new int[ms.length];
    28. next[0] = -1;
    29. next[1] = 0;
    30. int i = 2;
    31. int cn = 0;
    32. while (i < next.length) {
    33. if (ms[i - 1] == ms[cn]) {
    34. next[i++] = ++cn;
    35. } else if (cn > 0) {
    36. cn = next[cn];
    37. } else {
    38. next[i++] = 0;
    39. }
    40. }
    41. return next;
    42. }
    43. public static void main(String[] args) {
    44. String str = "abcabcababaccc";
    45. String match = "ababa";
    46. System.out.println(getIndexOf(str, match));
    47. }
    48. }