Repeated Substring Pattern

来源:互联网 发布:浩顺考勤机数据库 编辑:程序博客网 时间:2024/06/06 01:35

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: TrueExplanation: It's the substring "ab" twice.

Example 2:

Input: "aba"Output: False

Example 3:

Input: "abcabcabcabc"Output: TrueExplanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

这道题用了一个比较基础的解法,从长度为1 开始,从下表0开始取字串(字串的长度从1 ~ str.length-2)然后依次跟后面比较,如果都相同,那么说明是可以拼成的,否则不能。


代码:


public boolean repeatedSubstringPattern(String str) {        if(str == null || str.length() == 0) return true;        int len = str.length();        for(int i=1;i<len;i++){            if(len % i == 0){                String sub = str.substring(0, i);                boolean isSub = true;                for(int j=i;j<len;j++){                    if(sub.charAt(j%sub.length()) != str.charAt(j)){                        isSub = false;                        break;                    }                }                if(isSub){                    return true;                }            }        }        return false;    }



0 0