[LeetCode] Word Break, Solution
2013-11-19 14:02
316 查看
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 =
dict =
s =
"leetcode",
dict =
["leet", "code"]. Return true because
"leetcode"can be segmented as
"leet code". [Thoughts] 一个DP问题。定义possible[i] 为S字符串上[0,i]的子串是否可以被segmented by dictionary. 那么 possible[i] = true if S[0,i]在dictionary里面 = true if possible[k] == true 并且 S[k+1,j]在dictionary里面, 0<k<i = false if no such k exist. 实现时前面加一个dummy节点,这样可以把三种情况统一到一个表达式里面。 [code] bool wordBreak(string s, unordered_set<string> &dict) { string s2 = '#' + s; int len = s2.size(); vector<bool> possible(len, 0); possible[0] = true; for(int i =1; i< len; ++i) { for(int k=0; k<i; ++k) { possible[i] = possible[k] && dict.find(s2.substr(k+1, i-k)) != dict.end(); if(possible[i]) break; } } return possible[len-1]; }
相关文章推荐
- [LeetCode] Word Break, Solution
- Leetcode Solution – Word Break
- [LeetCode] Word Break, Solution
- [LeetCode] Same Tree, Solution
- LeetCode238 Product of Array Except Self(java and python solution)
- [LeetCode 1] Two Sum solution
- leetcode之Word Break
- [LeetCode 2] Add Two Numbers Solution
- [LeetCode] Single Number, Solution
- LeetCode: Scramble String, a naive recursion solution
- The Solution to Leetcode 118 Pascal's Triangle
- [LeetCode Solution 54] Spiral Matrix
- LeetCode_Word Break
- [Leetcode] Binary Tree Paths, Solution
- leetcode之Word Break
- Word Break - LeetCode
- LeetCode-Word Break-断词
- leetcode_solution_1
- [Leetcode] Word Break
- LeetCode 139. Word Break