Word Break

时间:2023-03-09 06:46:33
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"

给一个字符串s和一个字典dict,编程实现s能否由dict中组合而成。

方案一的DFS提交TLE,方案二使用动态规划

class Solution{
private:
void helper(string s,unordered_set<string>& wordDict,int start,bool& res){
if(start == int(s.length())){
res = true;
return;
}
for(int i = start;i<int(s.size());i++){
string word = s.substr(start,i - start + );
if(wordDict.find(word) != wordDict.end() && !res){ helper(s,wordDict,i+,res);
}
}
} public:
bool wordBreak(string s,unordered_set<string>& wordDict){
bool res = false;
helper(s,wordDict,,res);
return res;
}
}; class Solution2{
public:
bool wordBreak(string s,unordered_set<string>& wordDict){
vector<bool> res(s.size()+,false);
res[] = true; for(int i=;i<int(s.size())+;i++){
for(int j=;j<i;j++){
if(res[j] && wordDict.find(s.substr(j,i-j)) != wordDict.end()){
res[i] = true;
break;
}
}
}
return res.back();
}
};