代码随想录算法训练营day8|28 实现 strStr() 459 重复的子字符串
LeetCode 28. 实现 strStr()
题目链接: 28. 实现 strStr()
代码:
class Solution {
public:
void getNext(int *next, const string &s) {
int j = -1;
next[0] = j; //j表示前缀末尾
for(int i = 1; i < s.size(); i++) { //i表示后缀末尾
while(j >= 0 && s[i] != s[j + 1]) {
j = next[j]; //向前回退
}
if(s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if(needle.size() == 0)
return 0;
int *next = new int[needle.size()];
getNext(next, needle);
int j = -1;
for(int i = 0; i < haystack.size(); i++) {
while(j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j]; //向前回退
}
if(haystack[i] == needle[j + 1]) {
j++;
}
if(j == needle.size() - 1)
return i - needle.size() + 1;
}
return -1;
}
};
本题小结:使用kmp计算模式串前缀表,然后利用前缀表进行比对判断,最后输出。KMP经典思想:当出现字符串不匹配时,可以记录一部分之前已经匹配的文本内容,利用这些信息避免从头再去做匹配。
LeetCode 459. 重复的子字符串
题目链接: 459.重复的子字符串
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin());t.erase(t.end() - 1); //掐头去尾
if(t.find(s) != std::string::npos) return true; //r
return false;
}
};
前缀表统一减一的实现方式:
class Solution {
public:
void getNext (int* next, const string& s){
next[0] = -1;
int j = -1;
for(int i = 1;i < s.size(); i++){
while(j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if(s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
bool repeatedSubstringPattern (string s) {
if (s.size() == 0) {
return false;
}
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0) {
return true;
}
return false;
}
};
本题小结:判断字符串s是否由重复子串组成,只要两个s拼接在一起,里面还出现一个s的话,就说明由重复子串组成。