1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
public boolean kmpSearch(char[] text, char[] parten) { int partenLength = parten.length; int textLength = text.length; int[] prefix = new int[partenLength]; prefixTable(parten, prefix); move_prefix_table(prefix); int i = 0; int j = 0; boolean flag = false; while (i < textLength) { if (j == partenLength - 1 && text[i] == parten[j]) { flag = true; result = i - partenLength + 1; break; } if (text[i] == parten[j]) { i++; j++; } else { j = prefix[j]; if (j == -1) { i++; j++; } } } return flag; }
public void move_prefix_table(int[] prefix) { for (int i = prefix.length - 1; i > 0; i--) { prefix[i] = prefix[i - 1]; } prefix[0] = -1; }
public void prefixTable(char[] parten, int[] prefix) { int length = parten.length; prefix[0] = 0; int j = 0; int i = 1; while (i < length) { if (parten[i] == parten[j]) { prefix[i] = j + 1; i++; j++; } else { if (j == 0) { prefix[i] = 0; i++; } else { j = prefix[j - 1]; } } }
}
|