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"
.
使用动态规划法是很好解决的。
时间复杂度是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(); }