28. 实现 strStr()
题目链接:28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
class Solution {
//next不减1
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle.charAt(j) != haystack.charAt(i))
j = next[j - 1];
if (needle.charAt(j) == haystack.charAt(i))
j++;
if (j == needle.length())
return i - needle.length() + 1;
}
return -1;
}
public void getnext(int[] next, String s){
int j = 0;
next[0] = 0;
for(int i = 1; i < s.length(); i++){
while(j>0 && s.charAt(j) != s.charAt(i))
j = next[j-1];
if (s.charAt(j) == s.charAt(i))
j++;
next[i] = j;
}
}
}
总结:
KMP算法,next数组是前缀表,保存的是模式串需要从哪开始匹配。即下标i之前(包括i)的字符串中,有多大长度的相同前缀后缀,。
计算前缀表:next数组;
j:前缀表的长度,指向前缀表的最后一位
i:后缀表的最后一位。
next[i] 表示相同前后缀的长度,即j;
初始化:i=0;j=1,next[0]=0;
过程:如果s[i]与s[j]不相等,j就等于next[j-1]的值,就是回跳。直到相等或者j=0;
如果相等,则j+1;
最后next[i]=j
易混点:i,j,不仅仅在模式串中移动,在next数组中也起作用,两者要联系起来看。
459.重复的子字符串
题目链接:459. 重复的子字符串 - 力扣(LeetCode)
class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s.equals("")) return false;
int len = s.length();
s = " " + s;
char[] chars = s.toCharArray();
int[] next = new int[len + 1];
for (int i = 2, j = 0; i <= len; i++) {
while (j > 0 && chars[i] != chars[j + 1]) j = next[j];
if (chars[i] == chars[j + 1]) j++;
next[i] = j;
}
if (next[len] > 0 && len % (len - next[len]) == 0) {
return true;
}
return false;
}
}
字符串总结:
双指针;反转系列;KMP