[leetcode][DP] Word Break
来源:互联网 发布:淘宝标着极有家可信吗 编辑:程序博客网 时间:2024/06/10 21:18
题目:
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) {bool *res = new bool[s.size()];//res[i]表示s的0...i能否word breakmemset(res, false, s.size()*sizeof(bool));for (int i = 0; i < s.size(); ++i){if (wordDict.find(s.substr(0, i+1)) != wordDict.end()){res[i] = true;continue;}for (int j = i-1; j >= 0; --j){//注意j从后往前比从前往后更有效率,因为当后半部分叫短时更有可能匹配单词if (res[j] && wordDict.find(s.substr(j + 1, i-j)) != wordDict.end()){res[i] = true;break;}}}bool ret = res[s.size() - 1];delete[]res;return ret;}};时间复杂度O(n^2),空间复杂度O(n)
优化算法:table中只放入当前字符之前可以wordBreak的子串的下标,这样减少了无谓的遍历。
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s.empty() || wordDict.empty()) return false;vector<int> table;//table中存放当前字符之前能被wordBreak的子串的下标for (int i = 0; i < s.size(); ++i){string sCur = s.substr(0, i+1);if (wordDict.find(sCur) != wordDict.end()) table.push_back(i);else{for (int j =table.size()-1; j >= 0; --j){int index = table[j];string sWord = s.substr(index + 1, i-index);if (wordDict.find(sWord) != wordDict.end()){table.push_back(i);break;}}}}if(table.size() == 0) return false;return table[table.size() - 1] == s.size()-1;}};
0 0
- LeetCode Word Break (dp)
- Leetcode dp Word Break
- 【Leetcode】Word Break (DP)
- [leetcode][DP] Word Break
- [LeetCode.DP]Word Break ||
- LeetCode Word Break DP
- leetcode---word-break---dp
- LeetCode:Word Break(DP)
- LeetCode:Word Break II(DP)
- leetcode Word Break 字典树+dp
- [C++]LeetCode: 112 Word Break(DP)
- LeetCode 140. Word Break II (DP+DFS)
- [leetcode][DP][回溯] Word Break II
- [leetcode][DP][回溯] Word Break II
- LeetCode Word Break II DP+DFS
- Leetcode 139 - Word Break(线性dp)
- leetcode Word Break & Word Break ||
- Word Break ,dp
- CSAPP 深入理解计算机系统 Buflab实验,缓冲区溢出攻击实验(6)
- Codeforces D. Giving Awards 412(DFS)
- 面试总结-经验篇
- 泛型
- [leetcode] Reverse Linked List
- [leetcode][DP] Word Break
- Android Socket
- AIX 6.1 Oracle11g 11.2.0.4 RAC 安装心得
- 简述设计数据库的步骤
- jquery ajax 方法中传递的data参数,如何在java类中获取
- HDU - 2855 Fibonacci Check-up 矩阵快速幂
- 用Python和Pygame写游戏-从入门到精通(2)
- 缩略图缓存清除(仅win7)
- Android Service