class Solution {
public int strStr(String s1, String s2) {
if (s1.length() < s2.length()) return -1;
if(s2.length() == 0)return 0;
int i = 0, j = 0;
int[] next = getNextArr(s2);
while (i < s1.length() && j < s2.length()) {
if (s1.charAt(i) == s2.charAt(j)) {
i++;
j++;
} else if (next[j] == -1) {
i++;
} else {
j = next[j];
}
}
return j == s2.length() ? i - j : -1;
}
private static int[] getNextArr(String s) {
if (s.length() == 1) {
return new int[]{-1};
}
int[] next = new int[s.length()];
char[] carr = s.toCharArray();
next[0] = -1;
next[1] = 0;
int pre = 0, cur = 2;
while (cur < s.length()) {
if (carr[pre] == carr[cur - 1]) {
pre++;
next[cur++] = pre;
} else if (pre > 0) {
pre = next[pre];
} else {
next[cur++] = 0;
}
}
return next;
}
}
KMP算法
最新推荐文章于 2023-01-23 18:57:44 发布