[LeetCode] Word Break, Solution
来源:互联网 发布:男内裤 知乎 编辑:程序博客网 时间:2024/06/07 02:48
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"
.
[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.
[Code]
实现时前面加一个dummy节点,这样可以把三种情况统一到一个表达式里面。
1 bool wordBreak(string s, unordered_set<string> &dict) { 2 string s2 = '#' + s; 3 int len = s2.size(); 4 vector<bool> possible(len, 0); 5 6 possible[0] = true; 7 for(int i =1; i< len; ++i) 8 { 9 for(int k=0; k<i; ++k)10 {11 possible[i] = possible[k] && 12 dict.find(s2.substr(k+1, i-k)) != dict.end();13 if(possible[i]) break;14 }15 }16 17 return possible[len-1];18 }
0 0
- [LeetCode] Word Break, Solution
- [LeetCode] Word Break, Solution
- Leetcode Solution – Word Break
- Lintcode107 Word Break solution 题解
- leetcode Word Break & Word Break ||
- Leetcode: Word Break
- [leetcode]Word Break
- [leetcode]Word Break II
- LeetCode:Word Break
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break
- [LeetCode] Word Break II
- LeetCode: Word Break
- leetcode之Word Break
- [LeetCode]Word Break II
- [LeetCode]Word Break
- leetcode-Word Break
- Codeforces 507C - Guess Your Way Out! (思维)
- Install Linux Kernel - 通用标准
- Minimum Depth of Binary Tree leetcode
- Intent ( 意图 )
- Android 控件:ImageView、ProgressBar、AlertDialog、ProgressDialog
- [LeetCode] Word Break, Solution
- 使用node.js和socket.io实现多人聊天室
- WordPress4.1英文版转中文版
- Binary Tree Maximum Path Sum
- LeetCode Multiply Strings 高精度乘法C++实现
- Mac下安装Wordpress4.1英文版
- Longest Common Prefix
- 刨根问底U3D---Mono的配置
- 【学习排序】 Learning to Rank中Pointwise关于PRank算法源码实现