My Java solution with Regular expression


  • 0
    P
        public boolean repeatedSubstringPattern(String s) {
            String PATTERN = "(%s){2,}";
            int len = s.length();
            char c = s.charAt(len - 1);
            int end = s.indexOf(c);
            while (end >= 0 && end < s.length() / 2) {
                if (len % (end + 1) == 0 && s.matches(String.format(PATTERN, s.substring(0, end + 1)))) {
                    return true;
                }
                end = s.indexOf(c, end + 1);
            }
            return false;
        }
    

    the important point is len % (end + 1),it will skip unnecessary Comparison.
    if not ,you will get timeout.


Log in to reply
 

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