LeetCode练习-动态规划算法-word-break
来源:互联网 发布:灵格斯mac版 编辑:程序博客网 时间:2024/05/22 00:08
题目描述
Given a string s and a dictionary of words dict, determine ifs 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".
思路:首先我们要存储的历史信息res[i]是表示到字符串s的第i个元素为止能不能用字典中的词来表示,我们需要一个长度为n的布尔数组来存储信息。然后假设我们现在拥有res[0,...,i-1]的结果,我们来获得res[i]的表达式。思路是对于每个以i为结尾的子串,看看他是不是在字典里面以及他之前的元素对应的res[j]是不是true,如果都成立,那么res[i]为true,写成式子是
假设总共有n个字符串,并且字典是用HashSet来维护,那么总共需要n次迭代,每次迭代需要一个取子串的O(i)操作,然后检测i个子串,而检测是constant操作。所以总的时间复杂度是O(n^2)(i的累加仍然是n^2量级),而空间复杂度则是字符串的数量,即O(n)。
C++代码如下:
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { //bool *flag = new bool[s.length() + 1]; deque<bool> res(s.length() + 1, false); res[0] = true; int i, j; for (i = 0; i < s.length(); ++i){ for (j = 0; j <= i; ++j){ bool flag = false; if(dict.find(s.substr(j, i - j + 1)) != dict.end())//s[j...i] flag = true; if (res[j] && flag){ //s[0...j-1]是否满足条件 && s[j...i]是否满足条件 res[i + 1] = true; break; } } } return res[s.length()]; }};
本地测试代码:
bool wordBreak(string s, unordered_set<string> &dict);int main(){string s = "LeetCode";unordered_set<string> dict;dict.insert("Leet");dict.insert("Code");cout << wordBreak(s, dict) << endl;return 0;}
参考大神思路:http://blog.csdn.net/linhuanmars/article/details/22358863/
阅读全文
0 0
- LeetCode练习-动态规划算法-word-break
- [LeetCode] [动态规划] Word Break
- 【LeetCode】Word Break 动态规划
- 【LeetCode】Word Break II 动态规划
- '动态规划:word-break'
- 动态规划:word-break
- leetcode: Word Break 纪念又一次死在动态规划上
- 动态规划——Word Break 拆分词句【LeetCode】
- 139. Word Break 动态规划
- LeetCode练习-动态规划算法(一)
- LeetCode练习-动态规划算法(二)
- leetcode 动态规划练习
- Word Break II[动态规划&DFS]
- 动态规划问题系列---word break问题
- 牛客网第10题:动态规划 Word Break
- 13.12—动态规划—Word Break
- 动态规划、递归:word-break II
- leetcode 140. Word Break II 动态规划DP + DFS深度优先搜索
- Python学习笔记——列表
- JS数据结构之---数组
- 框架学习之springMVC整合框架-01基础、访问servletAPI、json
- Java面向对象-类与对象以及内存图解
- Birthday Paradox ||生日悖论
- LeetCode练习-动态规划算法-word-break
- 倍增LCA模板
- CSU
- Java中.getClass()和.class的区别
- Java设计模式学习07——桥接模式
- 排序算法---希尔排序(Shell Sort)
- Get方法中文传递参数乱码
- 神经网络与深度学习 1.3 神经网络的架构 1.4 一个简单的分类手写数字的网络架构
- 杭电 OJ 1219 AC Me