Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "catsanddog
" wordDict =["cat", "cats", "and", "sand", "dog"]
Output:[ "cats and dog", "cat sand dog" ]
Example 2:
Input: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output: [ "pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] Output: []
思路:
这道题和上一题其实是一样的,决解方案也相同。但是这一题有一个特殊用例,如果直接处理的话会导致超时或者超内存,需要先使用上一题的方法进行判断。
1 暴力搜索
void helper(string s, unordered_set<string> wordSet, string solution, vector<string>& res){
if (s.empty()){
res.push_back(solution);
return;
}
for (int i = 0; i < s.size(); i++){
string profix = s.substr(0, i + 1);
if (wordSet.find(profix) != wordSet.end()){
string nextSolution;
if (solution.empty())
nextSolution = profix;
else
nextSolution = solution + " " + profix;
string nextS = s;
nextS.erase(0, i + 1);
helper(nextS, wordSet, nextSolution, res);
}
}
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet;
for (string word : wordDict)
wordSet.insert(word);
vector<string> res;
helper(s, wordSet, "", res);
return res;
}
2 动态规划
bool check(string s, vector<string>& wordDict){
unordered_set<string> wordSet;
for (string word : wordDict)
wordSet.insert(word);
int sLen = s.size();
vector<bool> record(sLen, false);
for (int i = 0; i < sLen; i++){
string subS = s.substr(0, i + 1);
if (wordSet.find(subS) != wordSet.end()){
record[i] = true;
continue;
}
for (int j = 1; j < i + 1; j++){
string subS = s.substr(i - j + 1, j);
if (wordSet.find(subS) != wordSet.end())
record[i] = record[i - j] || record[i];
}
}
return record[sLen - 1];
}
vector<string> wordBreak2(string s, vector<string>& wordDict){
if (!check(s, wordDict)){
vector<string> v;
return v;
}
unordered_set<string> wordSet;
for (string word : wordDict)
wordSet.insert(word);
int len = s.size();
vector<vector<string>> res(len);
for (int i = len-1; i >= 0; i--){
string profix = s.substr(i, len - i);
if (wordSet.find(profix) != wordSet.end()){
res[i].push_back(profix);
}
for (int j = i + 1; j < len; j++){
string profix = s.substr(i, j-i);
if (wordSet.find(profix) != wordSet.end()){
for (string solution : res[j]){
res[i].push_back(profix + " " + solution);
}
}
}
}
return res[0];
}