459. Repeated Substring Pattern

来源:互联网 发布:卸载软件工具下载 编辑:程序博客网 时间:2024/06/06 00:25

题目:

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.)
思路:

求重复字符串,本题采用遍历比较的思想,重复项小于等于n/2,大于等于1

代码:

class Solution {public:    bool repeatedSubstringPattern(string s) {        int n = s.size();        for (int i = n / 2; i >= 1; --i) {            if (n % i == 0) {                int c = n / i;                string t = "";                for (int j = 0; j < c; ++j) {                    t += s.substr(0, i);                 }                if (t == s) return true;            }        }        return false;    }};