Fork me on GitHub

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

  思路:

判断s是否能够由子串重复生成,那么子串至少有两个,而且子串的长度最多也就s.length()/2个。那么可以模拟一下,如果
s.length()能够被[1...i...s.length()]中的i整除,说明子串长度为i,重复次数为s.length()/i ,判断由子串生成的字符串是否与s相等即可。
bool repeatedSubstringPattern(string s)
{
  int n = s.length();
  if(n<=1)return false;
  for(int i =1;i<=n/2;i++)
  {
    if(n%i==0)
    {
      string reps ="",sub = s.substr(0,i);
      for(int rep =0;rep<n/i;rep++)reps += sub;
      if(reps == s)return true;      
    }
  }
    return false;    
}

参考:

http://www.cnblogs.com/grandyang/p/6087347.html

posted @ 2017-07-18 21:01  hellowOOOrld  阅读(146)  评论(0编辑  收藏  举报