Clean JAVA Solution beat 90% (with explanation)


  • 0
    I

    First, we iterate to find the pattern with the same starting char, the the pattern length must less than or equal to half length of input string.
    If it is a valid string, the pattern length must be divided exactly.
    Then, we continuously check if the pattern could repeat through the whole string.

    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
            if (str.length() <= 1) return false;
            char[] c = str.toCharArray();
            for (int i = 1; i <= c.length / 2; i++) {
                if (c[0] == c[i] && c.length % i == 0) {
                    int times = c.length / i;
                    String cur = str.substring(0, i);
                    for (int j = 1; j < times; j++) {
                        if (!cur.equals(str.substring(j * i, j * i + i)))
                            break;
                        else if (j == times - 1)
                            return true;
                    }
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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