首页 > 代码库 > leetcode 139. Word Break
leetcode 139. 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"
.
[Solution]
对于S=“leetcode”, 我们用table[1...n]记录S[0...n-1]是否为dictionary word.
下面可以用动态规划求解。
假设已知table[1...k], 即已知S[0, ..., k-1]是否为dictionary word,那么
如果table[1] = true, 只要S[1, ..., k]是dictionary word, 则table[k] = true
如果table[2] = true, 只要S[2, ..., k]是dictionary word, 则table[k] = true
...
可得table[k + 1] = (FOR ANY i IN [0, k], IF table[i] = true && S[i, ..., k] IS DICT WORD)
1 bool wordBreak(string s, unordered_set<string> &dict) 2 { 3 vector<bool> table(s.size() + 1, false); 4 table[0] = true; 5 6 for (int i = 1; i <= s.size(); i++) 7 { 8 for (int j = 0; j < i; j++) 9 {10 if (table[j] == false)11 continue;12 if (dict.find(s.substr(j, i - j)) != dict.end())13 {14 table[i] = true;15 break;16 }17 }18 }19 20 return table[s.size()];21 }
leetcode 139. Word Break
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。