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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么抽出合适长度的重复单元

[一句话思路]:

小于i/2的长度,一个一个地能否被整除

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

手生还是有影响的:for j 又写成了i 

[总结]:

不知道长度就一个个数除着来

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        //cc
        if (s.length() == 0) {
            return true;
        }
        //for loop
        for (int i = s.length() / 2; i >= 1; i--) {
            if (s.length() % i == 0) {
                int m = s.length() / i;
                String sub = s.substring(0, i);
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < m; j++) {
                    sb.append(sub);
                }
                if(sb.toString().equals(s)) {
                    return true;
                }
            }
        }
        return false;
    }
}
View Code

 

posted @ 2018-03-24 21:07  苗妙苗  阅读(141)  评论(0编辑  收藏  举报