美文网首页
LeetCode459. Repeated Substring

LeetCode459. Repeated Substring

作者: Yuu_CX | 来源:发表于2016-11-16 09:18 被阅读0次

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: TrueExplanation: It's the substring "ab" twice.
Example 2:
Input: "aba"Output: False
Example 3:
Input: "abcabcabcabc"Output: TrueExplanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

C++:

class Solution {
public:
    bool repeatedSubstringPattern(string str) {
        int len = str.size();
        for(int i=len/2;i>0;i--){
            if(len%i==0){
                int n = len/i;
                string sub = str.substr(0,i);
                string sb;
                for(int j=0;j<n;j++){
                    sb += sub;
                }
                if(sb==str) return true;
            }
        }
        return false;
    }
};

Java:

public class Solution {
    public boolean repeatedSubstringPattern(String str) {
        int len = str.length();
        for(int i=len/2;i>0;i--){
            if(len%i==0){
                int n = len/i;
                String sub = str.substring(0,i);
                StringBuffer sb = new StringBuffer();
                for(int j=0;j<n;j++){
                    sb.append(sub);
                }
                if(sb.toString().equals(str)) return true;
            }
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:LeetCode459. Repeated Substring

      本文链接:https://www.haomeiwen.com/subject/wualpttx.html