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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容