【题目1】KMP算法详解
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
KMP算法详解
【Next数组求法】!!!
【例子2】
为什么是j=Next[j-1]:
当要比较得j=3的位置比较失败后,就应该退而求其次找到可能的前缀
aba(b) 不等于aba(a) ==> ab(a) 是否相等ba(a) ==> a(b) 是否相等a(b)
为什么直接跨国了中间,因为前面next数组已经计算出来,aba最大真前缀为1,只需要从j=1开始判断就行,从已经比较过的真前缀,和next可以直接定位到可能需要比较的值
// 方法一
class Solution {
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;
}
}
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 && haystack.charAt(i) != needle.charAt(j)) {
j = next[j - 1]; //回退到需要比较的地方
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == needle.length() ) {
return (i - needle.length() + 1);
}
}
return -1;
}
}
【题目2】
给定一个非空的字符串 s
,检查是否可以通过由它的一个子串重复多次构成。
思路:算出他们的Next数组找规律
class Solution {
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;
}
}
public boolean repeatedSubstringPattern(String s) {
if(s.length()==0) return false;
int[] next = new int[s.length()];
getNext(next,s);
if(next[s.length()-1] == 0) //最后一位为0的情况
return false;
return s.length() % (s.length() - next[s.length()-1]) == 0?true:false;
}
}