码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 139. Word Break

时间:2015-01-15 23:33:14      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4227361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!