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

给定非空字符串检查是否可以通过获取它的子字符串并将子字符串的多个副本附加在一起来构造它。 您可以假设给定的字符串仅由小写英文字母组成,其长度不超过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.)

解答:

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

详解:

从字符串的一半遍历到1,如果可以被原字符串长度整除,说明可以分成m个子串,取从0开始的第一个子串重复m遍,拼接起来若与原字符串相等,即表示原字符串可以被拆分成m个子串。

posted @ 2018-08-31 14:34  chan_ai_chao  阅读(131)  评论(0编辑  收藏  举报