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"
.
[LeetCode Source]
思路1:DFS暴力解决,搜索所有可能但是超时。
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s.size()==0) return false; return dfs(s,wordDict,""); } bool dfs(string s,unordered_set<string>& wordDict,string temp){ if(temp==s) return true; if(temp.size()>s.size()) return false; for(auto i=s.begin();i<s.end();++i){ if(dfs(s,wordDict,temp+*i)) return true; } return false; } };思路二:该题也可以采用动态规划解,效果好很多。写出状态转移方程。
F(i)表示字符串前i个字符是否可以wordbreak。
初始化F(0)=True,对于F(i)。
对所有小于i的j。
F(i) = F(j) + substr(i-j)(是否在Dict中),
如果有存在:F(i)=true.
class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { vector<bool> F(s.length()+1,false); F[0]=true; for(int i=1;i<s.length()+1;++i) for(int j=0;j<i;++j){ if(F[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){ F[i] = true; } } return F[s.length()]; } };