[LeetCode 459] Repeated Substring Pattern

給一個(gè)字符串,判斷這個(gè)字符串能不能被某一個(gè)子串完全重復(fù)分割。

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

分析:

能夠被某一個(gè)子串重復(fù)分割,就意味著這個(gè)子串的長度能夠整除總的字符串的長度
string.length % substring.length = 0


最長的子串可能滿足這個(gè)要求的,長度也只可能為 string.length / 2


思路:

先從index = 1開始截取子串
然后用一個(gè)指針往后遍歷當(dāng)前長度的子串,看是否跟原子串相同
如果遍歷到最后都是相同的,就返回true
如果整個(gè)字符串都截取完了都沒結(jié)果,就返回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;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容