第9天
前言
主要知识点
- KMP算法
- 28.实现strStr()
- 459.重复的子字符串
- 字符串总结
- 双指针简单回顾
前置知识
什么时KMP
三个学者发明的算法,算法名字三个学者名字的首字母
KMP有什么用
KMP主要用在字符串匹配上。
思想:当出现字符串不匹配时,可以知道一部分之前已经匹配的文本内容,可以利用这些信息避免从头再去做匹配了。
- 思路
- next数组主要是存取的最长公共前后缀长度
使用KMP算法记住四步:初始化,前后缀不相等的情况下,前后缀相等的情况下,next数组
- 初始化
i 表示的后缀末尾的长度
j表示前缀末尾长度
- 前后缀不相等的情况下:
前缀必须要大于0且前后缀不相等 j = next[ j - 1];
- 前后缀相等的情况下:j++
- 更新next数组 next[i] = j;
class Solution {
public void getNext(int[] next,String needle){
//获取next数组
// i后缀末尾位置
// j前缀末尾位置
int j = 0;
next[0] = 0; //在一个字符的情况下是没有最长公共前后缀长度
char[] s = needle.toCharArray();
for(int i = 1;i < s.length;i++){
while(j > 0 && s[i] != s[j]){
j = next[j - 1];
}
if(s[i] == s[j]){
j++;
}
next[i] = j;
}
}
public int strStr(String haystack, String needle) {
/*
初始化
前缀和后缀不相等
前缀和后缀相等
next数组
*/
if(needle.length() == 0){
return 0;
}
int[] next = new int[needle.length()];
int j =0;
getNext(next,needle);
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;
}
}
- 思路:
暴力枚举
字符串匹配
KMP(就这还简单,leetcode有点坑)
class Solution {
public String replaceSpace(String s) {
StringBuffer buffer = new StringBuffer();
for(int i = 0;i < s.length();i++){
if(s.charAt(i) == ' '){
buffer.append("%20");
}else{
buffer.append(s.charAt(i));
}
}
return buffer.toString();
}
}
字符串匹配
/*
如果您的字符串 S 包含一个重复的子字符串,那么这意味着您可以多次 “移位和换行”`您的字符串,并使其与原始字符串匹配。
*/
class Solution {
public boolean repeatedSubstringPattern(String s) {
String str = s+s;
return str.substring(1,str.length() - 1).contains(s);
/*
果S不包含重复的子字符串,则S本身就是所谓的“重复子字符串”(这里方便自己理解,视为重复一次,不深究= =),str = S+S,说明S是str的重复子字符串,刨去str首尾两个字符之后(相当于分别破坏前一个S头部和后一个S尾部),不能满足str包含S。
*/
}
}