Java 24ms solution beats 78%


  • 0
    S
    public boolean repeatedSubstringPattern(String str) {
    		int length = str.length();
    		for (int i = 2; i <= length; i++) {
    			if (length%i == 0){
    				int sl = length / i;
    				boolean isSame = false;
    				for (int j = 0; j < i-1; j++) {
    					if (str.substring(j*sl, (j+1)*sl).equals(str.substring((j+1)*sl, (j+2)*sl))){
    						isSame = true;
    					}else {
    						isSame = false; break;
    					}
    				}
    				if (isSame) return true;
    			}else{
    				continue;
    			}
    		}
    		return false;
    	}
    

  • 0
    N

    Do a little optimize, so that it would be 2ms faster :P)

    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
    		int length = str.length();
    		for (int i = 2; i <= length; i++) {
    			if (length%i == 0){
    				int sl = length / i;
    				boolean isSame = true;
    				for (int j = 0; j < i-1; j++) {
    				    int j0 = j * sl;
    				    int j1 = (j+1) * sl;
    				    int j2 = (j+2) * sl;
    					if (!str.substring(j0, j1).equals(str.substring(j1, j2))){
    						isSame = false; break;
    					}
    				}
    				if (isSame) return true;
    			}
    		}
    		return false;
    	}
    }
    

Log in to reply
 

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