Word Break II
来源:互联网 发布:淘宝怎么改价钱 编辑:程序博客网 时间:2024/06/18 08:06
Given a string s and a dictionary of words dict, add spaces ins to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
Solution:
class Solution {public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> res; unordered_set<string> unmatch; int minN = 0x3fffffff, maxN = 0xffffffff; for(auto d : wordDict) { minN = min(minN, (int)d.length()); maxN = max(maxN, (int)d.length()); } dfs(s, wordDict, unmatch, "", res, minN, maxN); return res; } void dfs(string s, unordered_set<string> &wordDict, unordered_set<string> &unmatch, string str, vector<string> &res, int minN, int maxN) { if(!s.length()) { if(!str.empty()) res.push_back(str.substr(0, str.length() - 1)); return ; } for(int i = minN; i <= min(maxN, (int)s.length()); ++i) { string prefix = s.substr(0, i); if(!wordDict.count(prefix)) continue; else { string postfix = s.substr(i); if(unmatch.count(postfix)) continue; else { int num = res.size(); dfs(postfix, wordDict, unmatch, str + prefix + " ", res, minN, maxN); if(res.size() == num) unmatch.insert(postfix); } } } }};
0 0
- Word Break && Word Break II
- Word Break && Word Break II
- [leetcode]Word Break II
- Word Break II
- Word Break II
- LeetCode:Word Break II
- Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- Word Break II
- Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- Word Break II
- Word Break II
- Struts 2 mapping interceptors to action
- 工厂方法
- Java 保留两位小数
- Android开发 打开文件 选择文件对话框
- Android 使用LeakCanary 检测内存泄露
- Word Break II
- IS--A与 Has-a 区别
- std::function与std::bind 函数指针
- Xcode 调试必知必会
- 第三周上机实践—项目1—顺序表的基本运算
- 一篇讲解动态规划算法不错的文章
- vi/vim基本使用方法
- CocoaPods安装和使用 (二)
- video js选项