Java 11ms beat 99.9% of solutions with explanation


  • 0
    Z

    if a string is constructed by multiple repeating substring, then the repeating time is either an even time (2, 4, etc) or an odd time(3, 5, etc).

    for even time of repeating, we just need to check if the first half of string equals the second half of the string.

    for odd time of repeating, divide the string into 3 parts, and compare them.

    public boolean repeatedSubstringPattern(String s) {
            int len = s.length();
    
           // repeating even time
            int mid = len/2;
            if (s.substring(0,mid).equals(s.substring(mid))) {
                return true;
            }
    
            // check odd time
            int one_third = len / 3;
            String sub = s.substring(0,one_third);
            if (sub.equals(s.substring(one_third,one_third*2))
                    && sub.equals(s.substring(one_third*2))) {
                return true;
            }
    
            // special case for string consists of one character.
            if (len % 2 == 1) {
                char c = s.charAt(0);
                for (int i=1; i<len; i++) {
                    if (s.charAt(i) !=c ) return false;
                }
                return true;
            }
    
            return false;
        }
    

  • 0
    C

    the testData will miss.
    "abcdefgabcdefgabcdefgabcdefgabcdefg"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.