[leetcode] 140.Word Break II
2015-09-01 14:03
441 查看
题目:
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”].
题意:
给定一个字符串,和一个词典。查看这个字符串可以由字典中的词组成。
思路:
采用动态规划加回溯。扫描到某个字符j的时候,往前查看到i,看i到j构成的字符串是否在字典中,然后看从第一个字符到第i-1个字符能否由字典中单词组成,能的话,则前j个字符可以分为两个部分,第一部分是前i个字符,第二部分是i到j这段,这两段都可以由字典种单词形成。状态转移方程如下:
if(s.substr(i, j-i) in dictionary ) && DP[i] != NULL, DP[j].push_back(i)
以上。
代码如下:
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”].
题意:
给定一个字符串,和一个词典。查看这个字符串可以由字典中的词组成。
思路:
采用动态规划加回溯。扫描到某个字符j的时候,往前查看到i,看i到j构成的字符串是否在字典中,然后看从第一个字符到第i-1个字符能否由字典中单词组成,能的话,则前j个字符可以分为两个部分,第一部分是前i个字符,第二部分是i到j这段,这两段都可以由字典种单词形成。状态转移方程如下:
if(s.substr(i, j-i) in dictionary ) && DP[i] != NULL, DP[j].push_back(i)
以上。
代码如下:
class Solution { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { if (s.empty())return vector<string>(); vector<vector<int>> DP(s.length() + 1, vector<int>()); DP[0].push_back(-1); for (int i = 1; i <= s.length(); i++) for (int j = 0; j < i; j++) { if (!DP[j].empty() && wordDict.find(s.substr(j, i - j)) != wordDict.end()) { DP[i].push_back(j); } } vector<string> result; list<string> temp; getResult(s, result, temp, DP, s.length()); return result; } void getResult(string &s, vector<string>& result, list<string>& temp, vector<vector<int>>& DP, int index) { if (index == 0) { string res = ""; for (auto t : temp) { if(res != "")res = res + " " + t; else res = t; } result.push_back(res); return; } for (auto i : DP[index]) { temp.push_front(s.substr(i, index - i)); getResult(s, result, temp, DP, i); temp.pop_front(); } } };
相关文章推荐
- Enterprise Architect使用教程
- 数学公式编辑器MathType破解版序列号
- css hack 大全
- iOS中scrollview是否要回弹
- asp.net 后台根据数据库中的值 利用js给select标签赋选中值
- Android Support ;v4、v7、v13的区别
- 给app嵌入广告ADBannerView
- onMeasure()方法详细介绍(一)--onMeasure()方法中测量一个空间的尺寸
- MySQL的create table as 与 like区别
- 泡完脚做一件事最养肝
- Web API系列
- IIS命令行启动
- 360个人软件发布所遭遇的情况
- Android 小贴士
- Android 国际化,资源文件
- QString QDate::toString ( const QString & format ) const
- 排序算法总结
- 一致性Hash算法(分布式算法)
- JS实现自动倒计时
- oracle分页