leetcode@ [139/140] Word Break & Word Break II

时间:2024-01-19 00:04:38

https://leetcode.com/problems/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"].

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

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(s.length() == ) return false; vector<bool> canBreak(s.length(), false);
for(int i=;i<s.length();++i) {
if(wordDict.find(s.substr(, i+)) != wordDict.end()) {
canBreak[i] = true;
continue;
}
for(int pre=;pre<i;++pre) {
if(canBreak[pre] && wordDict.find(s.substr(pre+, i-pre)) != wordDict.end()) {
canBreak[i] = true;
break;
}
}
} return canBreak[s.length()-];
}
};

https://leetcode.com/problems/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.

Return all such possible sentences.

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

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

class Solution {
public:
void findBreakPoint(vector<bool>& canBreak, string& s, unordered_set<string>& wordDict) {
for(int i=;i<s.length();++i) {
if(wordDict.find(s.substr(, i+)) != wordDict.end()) {
canBreak[i] = true;
continue;
}
for(int pre=;pre<i;++pre) {
if(canBreak[pre] && wordDict.find(s.substr(pre+, i-pre)) != wordDict.end()) {
canBreak[i] = true;
break;
}
}
}
}
void dfs(vector<string>& res, vector<string>& load, vector<bool>& canBreak, string& s, unordered_set<string>& wordDict, int idx) {
if(idx == s.length()-) {
string tmp = "";
for(int i=;i<load.size()-;++i) tmp += load[i] + " ";
if(load.size()>) tmp+=load[load.size()-];
res.push_back(tmp);
return;
} for(int nx=idx+;nx<s.length();++nx) {
if(canBreak[nx] && wordDict.find(s.substr(idx+, nx-idx)) != wordDict.end()) {
load.push_back(s.substr(idx+, nx-idx));
dfs(res, load, canBreak, s, wordDict, nx);
load.pop_back();
}
}
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> canBreak(s.length(), false);
vector<string> res; res.clear();
vector<string> load; load.clear(); findBreakPoint(canBreak, s, wordDict);
if(canBreak[s.length()-]) dfs(res, load, canBreak, s, wordDict, -);
return res;
}
};