即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

Repeated Substring Pattern相关疑难问题及解法

编程语言 u011809767 12℃ 0评论

问题描述:

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.

示例:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.
Input: "aba"

Output: False
Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

问题分析:

若是该字符串是某个子串重复出现组成,那我们就可以假定不同长度的子串,不断的循环遍历测试即可。

代码如下:

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int len = s.length();
        for(int i = 1;i <= len / 2;)
        {
         string pattern = s.substr(0,i);
         int j = i;
   for(;j < len; j += i)
   {
    if(s.substr(j,i) != pattern) break;
   }
   if(j == len) return true;
   while(len % ++i && i <= len / 2); 
  }
  return false;
    }
};


转载请注明:CodingBlog » Repeated Substring Pattern相关疑难问题及解法

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情