My Java Solution


  • 0
    T
     public boolean wordBreak(String s, Set<String> wordDict) {
        int strlen = s.length();
        int[] bp_arr = new int[strlen];
    
        if(strlen == 0 || strlen == 1){
            return wordDict.contains(s);
        }
    
        Arrays.fill(bp_arr,-2);
    
        bp_arr[0] = wordDict.contains(s.substring(0,1))? 0: -1;
        for(int i=1;i<strlen;i++){
            int j;
            int a = i;
            for( j = -1;j<=i;j++){
    
    
                if(wordDict.contains(s.substring(j+1,i+1)) && (j == -1 || bp_arr[j] != -1)) {
                    bp_arr[i] = j >0? j:0;
                    break;
                }
            }
            if(j == i+1){
                bp_arr[i] = -1;
            }
        }
    
    
        return (bp_arr[strlen-1] != -1);
    
    
    
    
    }

Log in to reply
 

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