字符串 2
找出匹配字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
思路
经典的KMP算法,重点:学会理解next数组,并熟练编写代码
算法详解链接
class Solution {
// KMP
public int strStr(String haystack, String needle) {
if(needle.length() == 0)
return 0;
int[] next = new int[needle.length()];
getNext(next,needle);
int j = -1;
for(int i = 0;i < haystack.length();i++){
while(j >= 0 && haystack.charAt(i) != needle.charAt(j + 1))
j = next[j];
if(haystack.charAt(i) == needle.charAt(j + 1))
j++;
if(j == needle.length() - 1)
return (i - needle.length() + 1);
}
return -1;
}
// 获取前缀表,相同前后缀的长度
// 最长公共前后缀
// 前缀表具有告诉我们当前位置匹配失败,跳到之前已经匹配过的地方的能力。
public void getNext(int[] next,String needle){
//前缀开始
int j = -1;
next[0] = j;
//后缀
for(int i = 1;i < needle.length();i++){
while(j >= 0 && needle.charAt(j + 1) != needle.charAt(i)) // 前后缀不相同了
j = next[i]; // 向前回退
if(needle.charAt(i) == needle.charAt(j + 1)) //相同的前后缀
j++;
next[i] = j;
}
}
}
重复字符串
给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。
思路
KMP求出next数组,
class Solution {
// 借助于KMP
public boolean repeatedSubstringPattern(String s) {
int[] next = getNext(s);
int len = s.length();
if(next[len- 1] != - 1 && (len % (len - (next[len - 1] + 1))) == 0)
return true;
return false;
}
int[] getNext(String s){
int j = -1;
int[] next = new int[s.length()];
for(int i = 1;i < s.length();i++){
while(j >= 0 && s.charAt(i) != s.charAt(j + 1))
j = next[i];
if(s.charAt(i) == s.charAt(j + 1))
j++;
next[i] = j;
}
return next;
}
}
如果 next[len - 1] != -1,则说明字符串有最长相同的前后缀(就是字符串里的前缀子串和后缀子串相同的最长长度)。
如果len % (len - (next[len - 1] + 1)) == 0 ,则说明数组的长度正好可以被 (数组长度-最长相等前后缀的长度) 整除 ,说明该字符串有重复的子字符串。
数组长度减去最长相同前后缀的长度相当于是第一个周期的长度,也就是一个周期的长度,如果这个周期可以被整除,就说明整个数组就是这个周期的循环。