重复的子字符串


最开始想的是暴力解法,但总是超时,后来问了chatgp,可以通过用substr来缩短时间。勉强通过,耗时还是很大。

点击查看代码
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
int count=1;
string temp;
while(count<=s.size()/2){
   temp=s.substr(0,count);
    if(s.size()%temp.size()==0){
   
   int i=0;int j=0;
for(i=count;i<s.size();i+=count){
    for(j=0;j<temp.size();j++){
        if(s[i+j]!=temp[j]){break;}
    }
    if(j!=temp.size()){break;}
}
if(i==s.size()){return true;}
    }
++count;
temp.clear();
}
return false; 
    }
};
看了卡哥的方法,最关键的就是要知道重复子字符串的长度应该为字符串减去公共前后缀部分的长度。 了解了kmp三种实现方法,还是原始的那种最适合。
点击查看代码
class Solution {
public:
void getnext(int *next,const string& s){
    int j=-1;
    next[0]=j;
    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) {
int next[s.size()];
getnext(next,s);
int sz=next[s.size()-1]+1;
int len=s.size();
int k=len-sz;
if(next[len - 1] != -1&&len%k==0){return true;}
else{return false;}
    }
};
posted @ 2024-01-14 10:54  yun-che  阅读(22)  评论(0)    收藏  举报