首页 > 代码库 > 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