[leetcode]Word Break II
来源:互联网 发布:西南财经网络 编辑:程序博客网 时间:2024/04/27 22:54
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = (int)s.size();
vector<vector<vector<string>>> dp(n + 1);
dp[0].push_back(vector<string>());
size_t max_len = 0;
vector<bool> buffer(256, false);
for (auto &str : dict) {
for (auto &c : str)
buffer[c] = true;
}
for (auto &c : s) {
if (!buffer[c])
return vector<string>();
}
for (auto &str : dict) {
max_len = max(max_len, str.size());
}
for (int i = 0; i < n; i++) {
for (int len = 1; i + len - 1 < n && len <= max_len; len++) {
string t = s.substr(i, len);
if (dict.count(t) > 0) {
for (auto vs : dp[i]) {
vs.push_back(t);
dp[i+len].push_back(vs);
}
}
}
}
vector<string> res;
for (auto &vs : dp[n]) {
string t;
for (size_t i = 0; i < vs.size(); i++) {
if (i == 0)
t += vs[i];
else
t += " " + vs[i];
}
res.push_back(t);
}
return res;
}
};
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = (int)s.size();
vector<vector<vector<string>>> dp(n + 1);
dp[0].push_back(vector<string>());
size_t max_len = 0;
vector<bool> buffer(256, false);
for (auto &str : dict) {
for (auto &c : str)
buffer[c] = true;
}
for (auto &c : s) {
if (!buffer[c])
return vector<string>();
}
for (auto &str : dict) {
max_len = max(max_len, str.size());
}
for (int i = 0; i < n; i++) {
for (int len = 1; i + len - 1 < n && len <= max_len; len++) {
string t = s.substr(i, len);
if (dict.count(t) > 0) {
for (auto vs : dp[i]) {
vs.push_back(t);
dp[i+len].push_back(vs);
}
}
}
}
vector<string> res;
for (auto &vs : dp[n]) {
string t;
for (size_t i = 0; i < vs.size(); i++) {
if (i == 0)
t += vs[i];
else
t += " " + vs[i];
}
res.push_back(t);
}
return res;
}
};
- [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
- poj 1456 Supermarket
- 免安装Oracle客户端使用PL/SQL(Server2008 R2 64位问题也可解决)
- 数据结构之 迪杰斯特拉最短路径算法
- Promise in AngularJS
- MYSQL配置说明
- [leetcode]Word Break II
- Eclipse
- 9) 常用函数对象functionobject [原创,泛型编程,自由下载转载,需注明出处]
- 电脑操作技术
- Foundation: Balanced Tree Search
- 【OSGi】OSGi如何解决Java模块化的不足
- C++类中拷贝构造函数详解
- [leetcode]Populating Next Right Pointers in Each Node II
- Android soundPool 不能播放声音问题