真的很难,只是把原理记住了,这里默写一遍.KML算法在从一个字符串找某一字符串中是否出现的场景下经常应用。
28力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
1.用内置函数的方法:
class Solution {
public int strStr(String haystack, String needle) {
int left = 0;
int right = needle.length()-1;
while(right < haystack.length()){
if(haystack.substring(left,right+1).equals(needle)){
return left;
}
right++;
left++;
}
return -1;
}
}
2.用KMP算法
class Solution {
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length()];
int j = 0;
nextBound(needle,next);
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;
}
public void nextBound(String s,int[] next){
int j = 0;
next[0] = 0;
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.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
方法一:KMP
class Solution {
public boolean repeatedSubstringPattern(String s) {
int j = 0;
int[] next = new int[s.length()];
nextBound(s,next);
int len = s.length();
int max = next[len - 1];
if(max != 0 && len % (len - next[len - 1]) == 0){
return true;
}
return false;
}
public void nextBound(String s,int[] next){
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;
}
}
}
方法二:
用内置函数:
class Solution {
public boolean repeatedSubstringPattern(String s) {
String doubleS = s + s;
if(doubleS.substring(1,doubleS.length() - 1).contains(s)){
return true;
}
return false;
}
}