28.找出字符串中第一个匹配的下标,strStr()
KMP
先求next数组,这个是首位置0,在不匹配的时候直接找前一位的next数组的值
class Solution {
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == needle.length()) {
return i - j + 1;
}
}
return -1;
}
public void getNext(int[] next, String s) {
int j = 0;
next[0] = j;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = next[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
j++;
}
next[i] = j;
}
}
}
459.重复的子字符串
next数组
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
int[] next = new int[n];
getNext(next, s);
return next[next.length - 1] > 0 && n % (n - next[next.length - 1]) == 0;
}
public void getNext(int[] next, String s) {
int j = 0;
next[0] = j;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = next[j-1];//***************important
}
if (s.charAt(i) == s.charAt(j)) {
j++;
}
next[i] = j;
}
}
}