modify code

pull/6/head
左程云 5 years ago
parent 47ff0ddf6d
commit 665358339e

@ -2,39 +2,41 @@ package class27;
public class Code01_KMP { public class Code01_KMP {
public static int getIndexOf(String s, String m) { public static int getIndexOf(String s1, String s2) {
if (s == null || m == null || m.length() < 1 || s.length() < m.length()) { if (s1 == null || s2 == null || s2.length() < 1 || s1.length() < s2.length()) {
return -1; return -1;
} }
char[] str = s.toCharArray(); char[] str1 = s1.toCharArray();
char[] match = m.toCharArray(); char[] str2 = s2.toCharArray();
int x = 0; int x = 0;
int y = 0; int y = 0;
int[] next = getNextArray(match); // O(M) m <= n
while (x < str.length && y < match.length) { int[] next = getNextArray(str2);
if (str[x] == match[y]) { // O(N)
while (x < str1.length && y < str2.length) {
if (str1[x] == str2[y]) {
x++; x++;
y++; y++;
} else if (next[y] == -1) { } else if (next[y] == -1) { // y == 0
x++; x++;
} else { } else {
y = next[y]; y = next[y];
} }
} }
return y == match.length ? x - y : -1; return y == str2.length ? x - y : -1;
} }
public static int[] getNextArray(char[] match) { public static int[] getNextArray(char[] str2) {
if (match.length == 1) { if (str2.length == 1) {
return new int[] { -1 }; return new int[] { -1 };
} }
int[] next = new int[match.length]; int[] next = new int[str2.length];
next[0] = -1; next[0] = -1;
next[1] = 0; next[1] = 0;
int i = 2; int i = 2; // 目前在哪个位置上求next数组的值
int cn = 0; int cn = 0; // 当前是哪个位置的值再和i-1位置的字符比较
while (i < next.length) { while (i < next.length) {
if (match[i - 1] == match[cn]) { if (str2[i - 1] == str2[cn]) { // 配成功的时候
next[i++] = ++cn; next[i++] = ++cn;
} else if (cn > 0) { } else if (cn > 0) {
cn = next[cn]; cn = next[cn];

@ -11,10 +11,11 @@ public class Code01_Manacher {
// 回文半径的大小 // 回文半径的大小
int[] pArr = new int[str.length]; int[] pArr = new int[str.length];
int C = -1; int C = -1;
// 讲述中R代表最右的扩成功的位置。coding最右的扩成功位置的再下一个位置 // 讲述中R代表最右的扩成功的位置
// coding最右的扩成功位置的再下一个位置
int R = -1; int R = -1;
int max = Integer.MIN_VALUE; int max = Integer.MIN_VALUE;
for (int i = 0; i < str.length; i++) { for (int i = 0; i < str.length; i++) { // 0 1 2
// R第一个违规的位置i>= R // R第一个违规的位置i>= R
// i位置扩出来的答案i位置扩的区域至少是多大。 // i位置扩出来的答案i位置扩的区域至少是多大。
pArr[i] = R > i ? Math.min(pArr[2 * C - i], R - i) : 1; pArr[i] = R > i ? Math.min(pArr[2 * C - i], R - i) : 1;

Loading…
Cancel
Save