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 + 1); if(wordDict.find(word) != wordDict.end() && !res){ helper(s,wordDict,i+1,res); } } } public: bool wordBreak(string s,unordered_set<string>& wordDict){ bool res = false; helper(s,wordDict,0,res); return res; } }; class Solution2{ public: bool wordBreak(string s,unordered_set<string>& wordDict){ vector<bool> res(s.size()+1,false); res[0] = true; for(int i=0;i<int(s.size())+1;i++){ for(int j=0;j<i;j++){ if(res[j] && wordDict.find(s.substr(j,i-j)) != wordDict.end()){ res[i] = true; break; } } } return res.back(); } };