139. Word Break

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".

Solution1:Round1 DP (应该Solution2)

思路:
Time Complexity: O(N) Space Complexity: O(N^2)

Solution2*:DP

思路:
DP,dp[i + 1] 表示0到以i结尾的str是ok的

Time Complexity: O(N) Space Complexity: O(N)

Solution1 Code:

class Solution {
    public boolean wordBreak(String s, List wordDict) {
        Set set = new HashSet<>();
        for(String str: wordDict) {
            set.add(str);
        }
        
        // t: tail
        for(int t = 0; t < s.length(); t++) {
            for(int i = 0; i < t; i++) {
                String part1 = s.substring(0, i + 1);
                String part2 = s.substring(i + 1, t + 1);
                if(set.contains(part1) && set.contains(part2)) {
                    set.add(s.substring(0, t + 1));
                }
            }
        }
        return set.contains(s);
    }
}

Solution2 Code:

class Solution {
    public boolean wordBreak(String s, List wordDict) {
        
        boolean[] dp = new boolean[s.length() + 1]; // dp[i + 1]: good for str that ends in i [tail]
        dp[0] = true;
            
        Set set = new HashSet<>();
        for(String str: wordDict) {
            set.add(str);
        }
        
        
        for(int n = 1; n < dp.length; n++) {
            int tail = n - 1;
            for(int i = 0; i <= tail; i++) {

                if(dp[i] && set.contains(s.substring(i, tail + 1))) {
                    dp[n] = true;
                    break;
                }
            }
        }
        
        return dp[dp.length - 1];
    }
}

你可能感兴趣的:(139. Word Break)