Leetcode Repeated Substring Pattern 459

来源:互联网 发布:艾弗森总决赛数据 编辑:程序博客网 时间:2024/05/05 23:17

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:
Input: “abab”

Output: True

Explanation: It’s the substring “ab” twice.
Example 2:
Input: “aba”

Output: False
Example 3:
Input: “abcabcabcabc”

Output: True

Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)

题目链接
考虑字符串的长度不超过10000.
使用一般的算法可以求解

class Solution {public:    bool repeatedSubstringPattern(string str) {        if(str.length()==0)             return false;        int len=str.length();        for(int i=1;i<len/2+1;i++){            if(len%i==0){                int cnt=len/i;                if(cnt==1) return false;                string substring="";                for(int j=0;j<i;j++){                    substring+=str[j];                }                bool mark=true;                //cout<<"cnt="<<cnt<<endl;                for(int j=0;j<cnt;j++){                    string temp="";                    for(int k=j*i;k<i*(j+1);k++){                        temp+=str[k];                    }                    //cout<<"temp="<<temp<<"  substring="<<substring<<endl;                    if(!judge(temp,substring)){                        mark=false;                        break;                    }                }                if(mark) return true;            }        }        return false;    }    bool judge(string t,string s){        int lent=t.length();        int lens=s.length();        if(lent!=lens) return false;        for(int i=0;i<lent;i++){            if(s[i]==t[i]) continue;            else{                return false;            }        }        return true;    }};

ac之后

觉得可以提高的两点:1.stl中很多算法可以直接使用,避免类似judge()的使用2.kmp算法可以更高效求解  补一下
0 0