Repeated Substring Pattern Leetcode

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

有repeat pattern的话整个string可以分成几个相同的部分,可以被某一个数整除。

先找出这个数,从str.length()/2开始。

如果某个数可以被整除,这个数就是repeat pattern的长度, str.length/这个数就是repeat pattern重复的次数。

如果次数 * repeat pattern等于原数组,就说明原数组是repeat string组成的string。

public class Solution {
    public boolean repeatedSubstringPattern(String str) {
        if (str == null) {
            return false;
        }
        for (int i = str.length() / 2; i >= 1; i--) {
            if (str.length() % i == 0) {
                StringBuilder s = new StringBuilder();
                int times = str.length() / i;
                for (int j = 0; j < times; j++) {
                    s.append(str.substring(0, i));
                }
                if (s.toString().equals(str)) {
                    return true;
                }
            }
        }
        return false;
        
    }
}

教训是不要被实习的内容所累。。。这个算法由于题目条件限制变得很简单。。。



posted @ 2017-01-16 10:46  璨璨要好好学习  阅读(158)  评论(0编辑  收藏  举报