459. 重复的子字符串
时间:2020年8月24日
知识点:字符串,KMP
题目链接: https://leetcode-cn.com/problems/repeated-substring-pattern/
题目
给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例1
输入:
“abab”
输出:
True
解释:
可由子字符串 “ab” 重复两次构成。
示例2
输入:
“aba”
输出:
False
示例3
输入:
“abcabcabcabc”
输出:
True
解释:
可由子字符串 “abc” 重复四次构成。 (或者子字符串 “abcabc” 重复两次构成。)
解法
- 暴力求解
- KMP 参考:KMP算法
- 双倍字符串,若一个字符串可以由它的一个子串重复多次构成,我们可以双倍字符串的第二个元素开始找单倍字符串,且找到位置不为单倍字符串的末尾
代码
#include <stdio.h>
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
for (int i = 1; i * 2 <= n; i++) {
if (n % i == 0) {
bool match = true;
for (int j = i; j < n; j++) {
if (s[j] != s[j - i]) {
match = false;
break;
}
}
if (match) {
return true;
}
}
}
return false;
}
};
/*
class Solution {
public:
bool kmp(const string& q, const string& p) {
int m = q.size();
int n = p.size();
vector<int> next(n,-1);
for(int i = 1;i < n; i++){
int j = next[i-1];
while(j != -1 && p[j+1] != p[i]){
j = next[j];
}
if(p[j+1] == p[i]){
next[i] = j+1;
}
}
int j = -1;
for(int i = 1;i < m-1; i++){
while(j != -1 && p[j+1] != q[i]){
j = next[j];
}
if(p[j+1] == q[i]){
++j;
if(j == n-1){
return true;
}
}
}
return false;
}
bool repeatedSubstringPattern(string s) {
return kmp(s + s, s);
}
};
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s+s).find(s, 1) != s.size();
}
};
*/
int main()
{
string s1 = "ABABCABAA";
string s2 = "ABABABABCABAAB";
Solution s;
cout<<s.kmp(s2, s1);
return 0;
}
今天也是爱zz的一天哦!