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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

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;
    }
};

   #Leetcode# 459. Repeated Substring Pattern 随笔

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

555~

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄