[LeetCode] Repeated Substring Pattern

Repeated Substring Pattern

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

Example 1: Input: "abab"ui

Output: Truecode

Explanation: It's the substring "ab" twice. Example 2: Input: "aba"ip

Output: False Example 3: Input: "abcabcabcabc"get

Output: Truestring

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)it

Time Complexity
O(k * n)
Space Complexity
O(n)io

思路

i means the length of the substring
len/i means how many substring in the stringim

finally check if the substring append len/i times equals the sdi

代碼

public boolean repeatedSubstringPattern(String s) {
    if(s == null || s.length() == 0) return false;
    int len = s.length();
    
    for(int i = 1; i <= len/2; i++){
        if(len % i == 0){
            int subStrLen = len/i;
            StringBuilder sb = new StringBuilder();
            String str = s.substring(0, i);
            for(int j = 0; j < subStrLen; j++){
                sb.append(str);
            }
            if(sb.toString().equals(s)) return true;
        }
    }
    return false;
}
相關文章
相關標籤/搜索