[LeetCode 459] Repeated Substring Pattern

给一个字符串,判断这个字符串能不能被某一个子串完全重复分割。

Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
Input: "aba"
Output: False

分析:

能够被某一个子串重复分割,就意味着这个子串的长度能够整除总的字符串的长度
string.length % substring.length = 0


最长的子串可能满足这个要求的,长度也只可能为 string.length / 2


思路:

先从index = 1开始截取子串
然后用一个指针往后遍历当前长度的子串,看是否跟原子串相同
如果遍历到最后都是相同的,就返回true
如果整个字符串都截取完了都没结果,就返回false


代码:

    public boolean repeatedSubstringPattern(String str) {
        if (str == null || str.length() == 0 || str.length() == 1) {
            return false;
        }
        // end index for every substring
        int endIndex = 1;
        // length of subStr cannot exceed half of str's length
        while (endIndex <= str.length() / 2) {
            if (str.length() % endIndex == 0) {
                String subStr = str.substring(0, endIndex);
                // total times we should traverse 
                int loopAmount = str.length() / endIndex;
                int i = 1;
                for (i = 1; i < loopAmount; i++) {
                    if (!subStr.equals(str.substring(endIndex * i, endIndex + endIndex * i))) {
                        break;
                    }
                }
                // if reaches the end of string, return true
                if (i == loopAmount) {
                    return true;
                }
            }
            endIndex++;
        }
        return false;
    }

你可能感兴趣的:([LeetCode 459] Repeated Substring Pattern)