Java simple accepted solution


  • 0
    M
    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
            if(str == null || str.isEmpty()) {
                return true;
            }
            
            int i = str.length()/2;
            while(i > 0) {
                if(str.length() % i == 0) {
                    if(repeated(str, str.substring(0, i))) {
                        return true;
                    }    
                }
                i--;
            }
            return false;
        }
        
        private boolean repeated(String s, String prefix) {
            if(s == null || s.isEmpty()) {
                return false;
            }
            
            if(s.length() < prefix.length()) {
                return false;
            }
    
            if(s.equals(prefix)) {
                return true;
            }
            
            if(!s.startsWith(prefix)) {
                return false;
            }
            
            return repeated(s.substring(prefix.length()), prefix);
        }
    }
    

Log in to reply
 

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