Java Solution 18ms


  • 0
    F
    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
            if(str.length()<2)return false;
            if(str.length()>1&&isPrime(str.length())&&str.charAt(0)!=str.charAt(1))return false;
            int parts = 2;
            while(parts<=str.length()){
                while(parts<str.length()&&(str.length()%parts!=0||!isPrime(parts))){
                    parts++;
                }
                int i = 1;
                int len = str.length()/parts;
                for(;i<parts;i++){
                    if(!str.substring(0,len).equals(str.substring(i*len,(i+1)*len)))break;
                }
                if(i==parts)return true;
                parts++;
            }
            return false;
        }
        public boolean isPrime(int a) {  
            boolean flag = true;
            if(a==2)return true;
            for (int i = 2; i <= Math.sqrt(a); i++) {  
                if (a % i == 0) {
                    flag = false;  
                    break;
                }  
            }  
            return flag;  
        }  
    }
    

Log in to reply
 

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