[LeetCode]Word Break, Word Break II

Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.優化

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

Return true because "leetcode" can be segmented as "leet code".code

分析

典型的DP題,dp[i]表示前i個字符是否可分解成單詞,那麼內存

dp[i] = dp[j] && dict.contains(s.substring(j, i)) (j = 0, 1, ..., i-1, 只要任意一個知足便可);

這道題不推薦用DFS,時間複雜度會很高,worst case達到O(2^n)。leetcode

這道題的Follow up,好比返回全部組合,或者只返回一個解,前者便是LeetCode原題Word Break II, 具體見下文。字符串

複雜度

time: O(n^2), space: O(n)get

代碼

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;
        
        for(int i = 1; i <= len; i++) {
            for(int j = 0; j < i; j++) {
                if(dp[j] && dict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[len];
    }
}

Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.string

Return all such possible sentences.io

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].class

A solution is ["cats and dog", "cat sand dog"].

分析

若是要返回全部組合的話,咱們能夠考慮兩種方法,一種是DP,時間複雜度較低,可是比較耗內存,意味着對於每一個Index, 咱們可能都要存其對應全部解。另外一種是DFS,空間複雜度較低,可是時間時間複雜度較高,咱們能夠採用memorization優化時間複雜度。

注意DP方法種爲了過OJ上一個edge case, 用Word Break的解法先檢測整個字符串是否可以分解,不能的話就沒有必要繼續算了。

複雜度

DP: time: O(n^2*k), space: O(nk), 假設k表示平均每一個長度對應解的個數
DFS: time: O(2^n), space: O(n)

代碼

DP

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        // 判斷是否可以分解
        if (!helper(s, wordDict)) {
            return new ArrayList<String>();
        }
        
        // 記錄字符串s.substring(0, i)對應的解
        HashMap<Integer, List<String>> map = new HashMap<Integer, List<String>>();
        map.put(0, new ArrayList<>());
        map.get(0).add("");
        
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (map.containsKey(j) && wordDict.contains(s.substring(j, i))) {
                    if (!map.containsKey(i))
                        map.put(i, new ArrayList<>());
                    for (String str : map.get(j)) {
                        map.get(i).add(str + (str.equals("") ? "" : " ") + s.substring(j, i));
                    }
                }
            }
        }
        
        return map.get(s.length());
    }
    
    private boolean helper(String s, Set<String> wordDict) {
        boolean dp[] = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                }
            }
        }
        return dp[s.length()];
    }
}

DFS

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> res = new ArrayList<String>();

        // 用來記錄s.substring(i)這個字符串可否分解         
        boolean[] possible = new boolean[s.length() + 1];
        Arrays.fill(possible, true);
        dfs(res, "", s, wordDict,  0, possible);
        return res;
    }
    
    public static void dfs(List<String> res, String cur, String s, Set<String> wordDict, int start, boolean[] possible) {
        if (start == s.length()) {
            res.add(cur);
            return;
        }
        for (int i = start + 1; i <= s.length(); i++) {
            String str = s.substring(start, i);
            if (wordDict.contains(str) && possible[i]) {
                int prevSize = res.size();
                dfs(res, cur + (cur.equals("") ? "" : " ") + str, s, wordDict, i, possible);
                
                // DFS後面部分結果沒有變化,說明後面是沒有解的    
                if (res.size() == prevSize)
                    possible[i] = false;
            }
        }
    } 
}
相關文章
相關標籤/搜索