Word Break
Given a stringsand a dictionary of wordsdict, determine ifscan 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".
使用动态规划法是很好解决的。
时间复杂度是O(n*n)。
形成这种思维需要不断锻炼,以前看这道题的时候觉得十分困难,现在终于觉得很容易的了。
评价为3到4星级吧。
//2014-2-19 update
bool wordBreak(string s, unordered_set<string> &dict)
{
vector<bool> tbl(s.length()+1);
tbl[0] = true;
for (int i = 0; i < s.length(); i++)
{
for (int d = 1, j = i; j >= 0; d++, j--)
{
if (tbl[j] && dict.count(s.substr(j, d)))
{
tbl[i+1] = true;
break;
}
}
}
return tbl.back();
}
本文介绍了一种利用动态规划解决WordBreak问题的方法,通过一个布尔型数组来记录字符串是否可以被字典中的单词完全匹配,实现了高效的空间分割判断。
529

被折叠的 条评论
为什么被折叠?



