[Leetcode]Word Break & Word Break II
来源:互联网 发布:android记账软件源码 编辑:程序博客网 时间:2024/06/04 19:40
Word Break is a problem that gives you a string and a dict of word, you have to indicate that if the string is a combination of the given words.
It is quite simple dp problem, the solution is like this.
dp[0] = 1;if dp[i]: dp[j] = 1 if str[i...j] in dict else 0
And the answer is true if dp[strlen(str)] is true, otherwise, it will return false.
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { memset(dp, 0, sizeof(dp)); dp[0] = 1; int len = s.length(); for (int i = 0; i <= len; i++) { if (dp[i]) { string tmp; for (int j = i + 1; j <= len; j++) { tmp += s[j - 1]; if (dict.find(tmp) != dict.end()) { dp[j] = 1; } } } } return dp[len]; } static const int SIZE = 1024; int dp[SIZE];};
Word Break II is an update version of previous problem. It needs you to point out how to construct the very string using given words.
So, we use an array of vector to store which words are used in this position.
At last, we dfs from right to left and make up the strings for the final answer.
class Solution {public: vector<string> wordBreak(string s, unordered_set<string> &dict) { for (int i = 0; i < SIZE; i++) { dp[i].clear(); } itos.clear(); stoi.clear(); ans.clear(); int idx = 0; for (auto iter = dict.begin(); iter != dict.end(); ++iter) { itos.push_back(*iter); stoi[*iter] = idx; idx++; } int len = s.length(); dp[0].push_back(-1); for (int i = 0; i <= len; i++) { if (!dp[i].empty()) { string ss; for (int j = i + 1; j <= len; j++) { ss += s[j - 1]; if (dict.find(ss) != dict.end()) { idx = stoi[ss]; dp[j].push_back(idx); } } } } string tmp; dfs(len, tmp); return ans; } void dfs(int pos, string& tmp) { if (pos == 0) { ans.push_back(tmp); return; } for (auto iter = dp[pos].begin(); iter != dp[pos].end(); ++iter) { string next; int now = *iter; if (tmp.empty()) { next = itos[now]; } else { next = itos[now] + " " + tmp; } dfs(pos - itos[now].size(), next); } } static const int SIZE = 1024; vector<string> ans; vector<int> dp[SIZE]; vector<string> itos; map<string, int> stoi;};
0 0
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Leetcode: Word Break II
- LeetCode Word Break II
- Word Break II leetcode
- [leetcode]Word Break II
- leetcode -- word break II
- 13.用二叉链表实现 二叉树的创建 遍历 4种
- 知码开门 装箱问题
- GL_INVALID_V
- HDU 2586
- uiautomator中AccessibilityNodeInfoDumper学习笔记(7)
- [Leetcode]Word Break & Word Break II
- Unauthorized request to start container
- 什么是僵尸进程(zombie)?
- POI导出到Excel的简单例子
- Spfa算法 (模板源代码)
- 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法
- SharePoint品牌化和自定义--创建会议工作区母版页
- 一个多月找实习的经历
- 黑马程序员——学习日记1 我的程序员之路