28. 实现 strStr()
class Solution {
// 求next数组
public void getNext(int[] next, String s){
int j = 0;
next[0] = j;
for(int i = 1; i < s.length(); i++){
// j未回退到开头且不匹配,需要回退
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) {
// 模式串为空,返回匹配长度0
if(needle.length() == 0){
return 0;
}
// 开辟next数组
int[] next = new int[needle.length()];
// 填充next数组
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++;
}
// debug点:匹配成功返回的应该是 i - needle.length() + 1
// 如果模式串匹配到了最后,说明已经匹配成功
if(j == needle.length()){
return (i - needle.length() + 1);
}
}
// 模式串未匹配到最后,文本串已扫描完成,
// 说明模式串匹配无效,返回-1
return -1;
}
}
题解2(两次kmp的next数组从-1开始,即前缀表-1):
class Solution {
// 求next数组
public void getNext(int[] next, String s){
int j = -1;
next[0] = j;
for(int i = 1; i < s.length(); i++){
// j未回退到开头且不匹配,需要回退
// 前缀表-1
while(j >= 0 && s.charAt(i) != s.charAt(j + 1)){
j = next[j];
}
// 匹配的情况
if(s.charAt(i) == s.charAt(j + 1)){
j++;
}
// 走到这里,或者匹配或者回退到头
next[i] = j;
}
}
public int strStr(String haystack, String needle) {
// 模式串为空,返回匹配长度0
if(needle.length() == 0){
return 0;
}
// 开辟next数组
int[] next = new int[needle.length()];
// 填充next数组
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++;
}
// debug点:匹配成功返回的应该是 i - needle.length() + 1
// 如果模式串匹配到了最后,说明已经匹配成功
if(j == needle.length() - 1){
return (i - needle.length() + 1);
}
}
// 模式串未匹配到最后,文本串已扫描完成,
// 说明模式串匹配无效,返回-1
return -1;
}
}
459.重复的子字符串
class Solution {
public boolean repeatedSubstringPattern(String s) {
// 移动匹配法
int n = s.length();
// debug点:不是substring(1,n-1),而是substring(1,n + n / 2)
return (s + s).substring(1,n + n / 2).contains(s);
}
}
class Solution {
public boolean repeatedSubstringPattern(String s) {
// KMP解法
// 若字符串为空,返回false
if(s.equals("")){
return false;
}
int len = s.length();
// 原串加空格,使下标从1开始
s = " " + s;
char[] ch = s.toCharArray();
int[] next = new int[len + 1];
// 构造next数组,j从0开始(空格),i从2开始
for(int i = 2,j = 0; i <= len; i++){
// 匹配失败
while(j > 0 && ch[i] != ch[j + 1]){
j = next[j];
}
// 匹配成功
if(ch[i] == ch[j + 1]){
j++;
}
// 更新next数组的值
next[i] = j;
}
// 最后判断是否是重复的子字符串,next[len]代表数组末尾的值
if(next[len] > 0 && len % (len - next[len]) == 0){
return true;
}
return false;
}
}