Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented 
into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".
public class Solution {
    // shoudl consider input, wordDict is small, check through string s
    //  O(n*m)  m for small Dict
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] canBreak = new boolean[s.length() + 1]; // s can be break from start to i;
        canBreak[0] = true;
        
        for(int i=0; i<= s.length(); i++){
            if(!canBreak[i]) continue;
            
            for(String word : wordDict) {   // renew each possible position with true
                int len = word.length();
                int end = i + len;
                // those unreachable position and reached position should ignore
                if(end > s.length() || canBreak[end]) continue;
                
                if(s.substring(i,end).equals(word)){
                    canBreak[end] = true;
                }
            }
        }
        
        return canBreak[s.length()];
    }
}
/*
//Second DP
        put list<String> into Set<String>           
        O(n^2) time two nested for loop
        O(K) for Dict
        for(int i=1; i <= s.length(); i++){         // fix the ending, find the starting, then compare middle
            for(int j=0; j < i; j++){
                if(f[j] && dict.contains(s.substring(j, i))){
                    f[i] = true;
                    break;
                }
            }
        }
*/

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。