459. Repeated Substring Pattern

Description

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

Solution

Basic

Brute-force with optimisation

public class Solution {
    public boolean repeatedSubstringPattern(String s) {
        if (s == null || s.length() < 2) {
            return false;
        }
        
        int len = s.length();
        boolean isValid = true;
        
        for (int subLen = 1; subLen <= len / 2; ++subLen) {     
            if (len % subLen != 0)  continue;   // do some math to filter obvious invalid subLen
            isValid = true;     // a flag use to break nested loop
            
            for (int i = subLen; isValid && i <= len - subLen; i += subLen) {
                for (int j = 0; isValid && j < subLen; ++j) {
                    if (s.charAt(j) != s.charAt(i + j)) isValid = false;
                }
            }
            
            if (isValid) return true;
        }
        
        return false;
    }
}

TODO: Optimisation

KMP

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容