首页 > 其他 > 详细

Repeated Substring Pattern --重复字符串

时间:2017-10-28 10:47:54      阅读:218      评论:0      收藏: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.

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


分析:
   1.重复字符串的长度肯定会被输入字符串长度整除
   2.遍历可能的重复字符串长度i,从s.length/2开始,不可能大于字符串的一半
   3.如果有个i被输入字符串整除,那么将该(0,i)的字符串合并
   4.与原字符串相比较,如果相等,则为重复字符串。

实现代码如下:
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int len = s.length();
        for(int i = len/2; i>=1;i--){
            if(len%i == 0){
                int m = len/i;  //代码有m个长度为i的重复字符串
                String str = s.substring(0, i);  //取出(0,i)的字符串
                StringBuffer sb = new StringBuffer();
                for(int j = 0;j < m;j++){
                    sb.append(str);
                }
                if(sb.toString().equals(s)){
                    return true;
                }
            }
        }
        return false;
    }
}

Repeated Substring Pattern --重复字符串

原文:http://www.cnblogs.com/linwx/p/7745971.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!