123_leetcode_Word Break II
来源:互联网 发布:苏州基本办公软件 编辑:程序博客网 时间:2024/05/23 19:14
Given a string s and a dictionary of words dict, add spaces in s 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"]
.
vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> result; if(s.length() < 1 || dict.size() == 0) { return result; } unordered_set<string>::iterator itr = dict.begin(); unsigned long maxLength = (*itr).length(); unsigned long minLength = (*itr).length(); while(++itr != dict.end()) { if ((*itr).length() > maxLength) { maxLength = (*itr).length(); } if((*itr).length() < minLength) { minLength = (*itr).length(); } } set<string> unMatch; vector<string> path; wordBreakCore1(s, dict, unMatch, maxLength, minLength, result, path); return result; } void wordBreakCore1(string s, unordered_set<string> &dict, set<string> &unMatch, unsigned long maxLength, unsigned long minLength, vector<string> &result, vector<string> &path) { if(s.size() == 0) { return; } unsigned long mx = s.length() < maxLength ? s.length() : maxLength; for(int i = (int)mx; i >= minLength; i--) { string tmpWord = s.substr(0, i); if(dict.find(tmpWord) != dict.end()) { path.push_back(tmpWord); if(tmpWord.length() == s.length()) { string tmp = path[0]; for(int j = 1; j < (int)path.size(); j++) { tmp = tmp + " "; tmp = tmp + path[j]; } result.push_back(tmp); } string leftStr = s.substr(i); if(unMatch.find(leftStr) == unMatch.end()) { int number = (int)result.size(); wordBreakCore1(leftStr, dict, unMatch, maxLength, minLength, result, path); if(number == (int)result.size()) { unMatch.insert(leftStr); } } path.pop_back(); } } }
0 0
- 123_leetcode_Word Break II
- 148_leetcode_Word Ladder II
- 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
- 我为什么要谈KeepAlive
- Scilab 的绘图函数(4)
- Socket 出现的各种异常分析
- Log4j 2.0在开发中的高级使用详解—默认级别(二)
- 判断一个字符串是否为数值型字符串
- 123_leetcode_Word Break II
- SaaS促进软件企业的二次转型
- CF 257DIV2 B. Jzzhu and Sequences (取余需注意!!!!!!!)
- 单例模式(Singleten Pattern)
- OCP 1Z0 053 174
- 不容错过!开发者必备的十二大Android开发资源
- 3D MAX导出插件编写
- Extjs4.2+struts2+swfupload多文件上传
- Android wear环境搭建