28. 实现 strStr()
滑动窗口实现(Om*n)
class Solution {
//滑动窗口 先找到首字母匹配
public int strStr(String haystack, String needle) {
int m = needle.length();
if(m == 0){
return 0;
}
int n = haystack.length();
if(n < m){
return -1;
}
int i = 0;
int j = 0;
while(i <= n - m ){
//遍历长字符串 先找到首字母匹配
while(i < n && haystack.charAt(i) != needle.charAt(j)){
i++;
}
//没有首字母相等 遍历到最后
if(i == n){
return -1;
}
//找到首字母相同 遍历后续是否相等
i++;
j++;
while(i < n && j < m && haystack.charAt(i) == needle.charAt(j)){
i++;
j++;
}
//找到
if(j == m){
return i - j;
}else{
i =i - j + 1; //i往后加一位
j = 0;
}
}
return -1;
}
}
KMP算法实现(时间复制度为 O(m+n))
KMP算法使用场景:给你一个字符串,判断另一个字符串是否在这个字符串里出现过
KMP的经典思想就是:当出现字符串不匹配时,可以记录一部分之前已经匹配的文本内容,利用这些信息避免从头再去做匹配(跳到上一次匹配的地方继续匹配)。
aabaabaaf
aabaaf
KMP算法作用:当匹配到b,f时,不会从头再次匹配,而是从上一次匹配到的地方继续匹配,例如上一次匹配到b是什么时候(找到下标)
思路:先计算出前缀表next 通过前缀 j+1 后缀 i,当不匹配通过next找到回退位置
class Solution {
//KMP算法 获取next数组
public void getNext(int[] next,String s){
int j = -1;
next[0] = j;
for(int i = 1;i < s.length;i++){
//前后缀不相同 前缀一直回退
while(j >= 0 && s.charAt(i) != s.charAt(j+1)){
j = next[j];
}
//前后缀相同,j++
if(s.charAt(i) == s.charAt(j+1)){
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 = -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);
}
}
}
}
459.重复的子字符串
思路:利用字符串重复构成的性质,如果一个字符串可以由一个子串重复构成,那么将原字符串拼接一次后去掉首尾子串,如果新字符串仍然包含原字符串,则说明原字符串可以由一个子串重复构成,字符串abab s + s a b(abab)a b
class Solution {
public boolean repeatedSubstringPattern(String s) {
String str = s+s;
return str.substring(1,str.length()-1).contains(s);
}
}