leetcode || 140、Word Break II
来源:互联网 发布:软件行业人才需求 编辑:程序博客网 时间:2024/04/28 22:43
problem:
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"]
.
thinking:
1 使用二维表vector<vector<int> >tbl记录,记录从i点,能否跳到下一个break位置。如果不能,那么tbl[i]就为空。如果可以,就记录可以跳到哪些位置。
2 利用二维表优化递归回溯法。
优化点:
如果当前位置是start,但是tbl[start]为空,那么就是说,这个break位置不能break整个s串的,直接返回上一层,不用搜索到下一层了。
code:
class Solution {public:vector<string> wordBreak(string s, unordered_set<string> &dict) {vector<string> rs;string tmp;vector<vector<int> > tbl = genTable(s, dict);word(rs, tmp, s, tbl, dict);return rs;}void word(vector<string> &rs, string &tmp, string &s, vector<vector<int> > &tbl,unordered_set<string> &dict, int start=0){if (start == s.length()){rs.push_back(tmp);return;}for (int i = 0; i < tbl[start].size(); i++){string t = s.substr(start, tbl[start][i]-start+1);if (!tmp.empty()) tmp.push_back(' ');tmp.append(t);word(rs, tmp, s, tbl, dict, tbl[start][i]+1);while (!tmp.empty() && tmp.back() != ' ') tmp.pop_back();//tmp.empty()if (!tmp.empty()) tmp.pop_back();}}vector<vector<int> > genTable(string &s, unordered_set<string> &dict){int n = s.length();vector<vector<int> > tbl(n);for (int i = n - 1; i >= 0; i--){if(dict.count(s.substr(i))) tbl[i].push_back(n-1);}for (int i = n - 2; i >= 0; i--){if (!tbl[i+1].empty())//if we can break i->n{for (int j = i, d = 1; j >= 0 ; j--, d++){if (dict.count(s.substr(j, d))) tbl[j].push_back(i);}}}return tbl;}};
0 0
- LeetCode: Word Break II [140]
- [leetcode 140] Word Break II
- LeetCode(140) Word Break II
- leetcode || 140、Word Break II
- leetcode 140: Word Break II
- 140 Word Break II [Leetcode]
- leetcode-140-Word Break II
- LeetCode 140 Word Break II
- LeetCode #140: Word Break II
- Leetcode 140 Word Break II
- Leetcode 140 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
- Android使用SSL
- 最大连续子序列和
- 博客转移
- iOS7隐藏状态栏 status Bar
- XSS Cheat Sheet
- leetcode || 140、Word Break II
- DDoS的攻击原理与防御方法
- enet学习(二):enet_peer_send()函数
- 严重: Exception sending context initialized event to listener instance of class org.springframework.we
- 工业4.0
- JavaWeb高级
- Python属性和方法
- 浅谈一下线程中synchronized块、wait,notify的用法
- 黑马程序员——Java学习笔记 数组