LeetCode OJ Word Break
来源:互联网 发布:理解信息与数据 编辑:程序博客网 时间:2024/06/05 23:59
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"
.
DP:
first dp:
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { vector<short> isOK(s.size() + 1, 0); isOK[s.size()] = 1; for (int i = s.size() - 1; i >= 0; i--) { for (int j = i; j < s.size(); j++) { if (dict.find(s.substr(i, j - i + 1)) != dict.end() && isOK[j + 1]) { isOK[i] = 1; break; } } } return isOK[0]; }};
The thought is :
This dp is from the bottom. Suppose the string is "abcdefghijk", the word break is successful when "abcde" is in the dictionary and "fghijk" is successfully word break.
So, isOK[i] means the substr starting from i is successfully word break. In the inner loop, if we found a substr from i to j is in the dictionary and the rest substr from j + 1 to the end is OK, then isOK[i] = 1.
Notice that isOK[s.size()] = 1 because the substr is empty.
second dp:
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { vector<short> isOK(s.size() + 1, 0); isOK[0] = 1; for (int i = 1; i <= s.size(); i++) { for (int j = 1; j <= i; j++) { if (dict.find(s.substr(j - 1, i - j + 1)) != dict.end() && isOK[j - 1]) { isOK[i] = 1; break; } } } return isOK[s.size()]; }};
Notice that isOK[0] is just a start sign of 0 length, which is always true, so the i and j start from 1 but they both point to s[i - 1] or s[j - 1].
0 0
- LeetCode OJ:Word Break
- LeetCode OJ - Word Break
- LeetCode OJ Word Break
- LeetCode OJ:Word Break II
- LeetCode OJ - Word Break II
- LeetCode OJ——Word Break
- [LeetCode OJ] Word Break II 解题报告
- [LeetCode OJ] Word Break 解题报告
- LeetCode OJ 之 Word Break (断词)
- leetcode Word Break & Word Break ||
- LeetCode OJ 之 Word Break II (断词 - 二)
- 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 OJ Minimum Depth of Binary Tree
- Python 编码知识学习笔记
- 网站架构的演变过程
- LeetCode OJ Maximum Depth of Binary Tree
- CSS3 弹性盒布局说明(CSS3 Flexible Box Layout Explained)
- LeetCode OJ Word Break
- 自己写一个简单的Web服务器(附Demo)
- (转)Hbase访问方式之Mapreduce
- 多动画集在D3D下的渲染
- uva 10029 HASH + DP
- UVALive - 4015 Caves 树形DP
- LeetCode OJ Binary Tree Preorder Traversal
- [LeetCode 48]Rotate Image
- 第二周项目1旱冰场造价