单词拆分

139. 单词拆分

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:

输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
     注意你可以重复使用字典中的单词。
示例 3:

输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
public class Onehundred_thirtyNine {
    public boolean wordBreak(String s, List wordDict) {
        /**
         * dp[i]表示s中以i-1结尾的字符串是否可以被worddict拆分
         * **/
        if (s == null || s.length() == 0)
            return false;
        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] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[len];
    }
}
class Solution {
public:
    bool wordBreak(string s, vector &wordDict) {
        if (s.size() == 0)
            return false;
        vector dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = 1; i <= s.size(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] == true && find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end()) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};

140. 单词拆分 II

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
  "cats and dog",
  "cat sand dog"
]
示例 2:

输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:

输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]
package gongel_second;

import java.util.ArrayList;
import java.util.List;

public class Onehundred_forty {
    /**
     * 先用139题的方法检测能否拆分,然后用dfs方法回溯
     */
    public List ans = new ArrayList<>();

    public boolean judge(String s, List wordDict) {
        if (s == null || s.length() == 0)
            return false;
        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] == true && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

    public void dfs(String s, List wordDict, List temp) {
        if (s == null)
            return;
        for (String str : wordDict) {
            if (s.startsWith(str)) {
                if (s.length() == str.length()) {//最后一个词,说明拆分成功
                    temp.add(str);
                    String tem = String.join(" ", temp);
                    ans.add(tem);
                    temp.remove(temp.size() - 1);
//                    return;//这里不能直接return,否则会导致str不能被重复利用
                } else {
                    temp.add(str);
                    dfs(s.substring(str.length()), wordDict, temp);
                    temp.remove(temp.size() - 1);
                }

            }
        }
    }

    public List wordBreak(String s, List wordDict) {
        if (judge(s, wordDict))
            dfs(s, wordDict, new ArrayList<>());
        return ans;
    }
}
class Solution {
public:
    vector wordBreak(string s, vector &wordDict) {
        unordered_map<string, vector> map;
        helper(s, wordDict, map);
        return map[s];
    }

    vector helper(string s, vector wordDict, unordered_map<string, vector> &map) {
        if (map.count(s))
            return map[s];
        if (s.empty())
            return {""};
        vector ans;
        for (auto word:wordDict) {
            if (s.substr(0, word.size()) != word)
                continue;
            vector temp = helper(s.substr(word.size()), wordDict, map);
            for (auto element:temp) {
                ans.push_back(word + (element.empty() ? "" : " " + element));
            }
        }
        map[s] = ans;
        return ans;
    }


    //方法2,和131题几乎一样,不加judge会超时
    vector wordBreak2(string s, vector &wordDict) {
        if (s.empty() || wordDict.empty())
            return {};
        vector temp;
        vector<vector> ans;
        dfs(s, wordDict, temp, ans);
        vector final;
        for (auto option:ans) {
            string str;
            for (int i = 0; i < option.size(); i++) {
                if (i == option.size() - 1)
                    str += option[i];
                else
                    str += option[i] + " ";
            }
            final.push_back(str);
        }
        return final;
    }

    void dfs(string s, vector wordDict, vector &temp, vector<vector> &ans) {
        if (s.empty()) {
            ans.push_back(temp);
            return;
        }
        for (auto word:wordDict) {
            if (s.substr(0, word.size()) == word && judge(s, wordDict)) {
                temp.push_back(word);
                dfs(s.substr(word.size()), wordDict, temp, ans);
                temp.pop_back();
            }
        }
    }

    bool judge(string s, vector &wordDict) {
        if (s.size() == 0)
            return false;
        vector dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = 1; i <= s.size(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] == true && find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end()) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};

return the last

0