#Leetcode# 459. Repeated Substring Pattern

 

https://leetcode.com/problems/repeated-substring-pattern/

 

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.)

代码:

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        vector<int> ans;
        int len = s.length();
        if(len == 1) return false;
        for(int i = 1; i * i <= len; i ++) {
            if(len % i == 0) {
                if(i != 1) {
                    ans.push_back(i);
                    ans.push_back(len / i);
                } else ans.push_back(1);
            }
        }
        int cnt = 0;
        for(int i = 0; i <ans.size(); i ++) {
            cnt = 0;
            string t = s.substr(0, ans[i]);
            for(int j = 0; j < len; j += ans[i]) {
                if(t == s.substr(j, ans[i]))
                    cnt ++;
                else break;
            }
            if(cnt == len / ans[i]) return true;
        }
        return false;
    }
};

  

  要特判一下如果字符串长度只有 1 是 false

555~

posted @ 2019-04-11 20:22  _Zlrrr  阅读(191)  评论(0)    收藏  举报