首页 > 代码库 > 459. Repeated Substring Pattern

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


判断一个字符串是否由一个相同子串构成

C++(43ms):
 1 class Solution {
 2 public:
 3     bool repeatedSubstringPattern(string s) {
 4         int len = s.size() ;
 5         for(int i = len/2 ; i>=1 ; i--){
 6             if(len%i == 0){
 7                 int m = len/i ;
 8                 string leftStr = s.substr(0,i) ;
 9                 string t = "" ;
10                 while(m--){
11                     t += leftStr ;
12                 }
13                 if(t == s)
14                   return true ;
15             }
16         }
17         return false ;
18     }
19 };

 

459. Repeated Substring Pattern