Share my clean Java code


  • 0
    T
    public static boolean wordBreak(String s, Set<String> dict) {  
    	
    	boolean[] canBreak = new boolean[s.length()];
    	int pos = 0;
    	
    	while(pos < s.length()){
    		if(dict.contains(s.substring(0, pos + 1))){
    			canBreak[pos] = true;
    			break;
    		}
    		canBreak[pos] = false;
    		pos ++;
    	}
    	
    	for(int i = pos + 1; i < s.length(); i ++){
    		for(int j = pos; j < i; j ++){
    			if(dict.contains(s.substring(0, i + 1))){
    				canBreak[i] = true;
    				break;
    			}
    			if(canBreak[j] && dict.contains(s.substring(j + 1, i + 1))){
    				canBreak[i] = true;
    				break;
    			}
    			canBreak[i] = false;
    		}
    	}
    	
    	return canBreak[s.length() - 1];
    }

  • 0
    C

    Hi, nice solution that works fine. However, I don't think the first while loop was necessary. You can iterate the string, at each index(i), first check substring(0, i+1), if contains then mark it to true, if not, for(j = 0; j <= i; j++) and check canBreak[j] && contains(substring(j + 1, i + 1)), or is there a reason you added the first while loop?


Log in to reply
 

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