leetcode:Word Break
来源:互联网 发布:mac os 10.7 dmg 下载 编辑:程序博客网 时间:2024/06/14 00:29
题目:https://oj.leetcode.com/problems/word-break/
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"
.
可以用DP的方法解决。
用数组wb[i]保存从0开始到长度为i的子串能否被分割,所以最后的结果返回wb[s.size() - 1]。
首先wb[0] = true.则wb[1]可分割的条件是:wb[0] == true且子串s[0]包含在字典中...wb[i] == true的条件是:存在0 <= j < i,使得从开始长度为j的子串可分割且从j到i的子串存在在字典中...以此类推求出所有的wb[i]...
AC代码:
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { int len = s.size(); //创建数组wb[i]表示从0开始长度为i的子串能否被分割;最后的答案则是wb[len] vector<bool> wb(len + 1,false); wb[0] = true; for(int i = 1;i <= s.size();i++){ for(int j = i - 1;j >= 0;j--){ //如果从开始长度为j的子串可以分割而且从j到i的子串出现在字典中 //则从开始长度为i的子串也可以分割 if(wb[j] && dict.count(s.substr(j,i - j))){ wb[i] = true; break; } } } return wb[len]; }};
0 0
- leetcode Word Break & Word Break ||
- Leetcode: Word Break
- [leetcode]Word Break
- [leetcode]Word Break II
- LeetCode:Word Break
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break
- [LeetCode] Word Break II
- LeetCode: Word Break
- leetcode之Word Break
- [LeetCode]Word Break II
- [LeetCode]Word Break
- leetcode-Word Break
- LeetCode 之 Word Break
- leetcode word break
- LeetCode | Word Break
- LeetCode | Word Break II
- Python下校验一个字符串是否为ip地址
- java小知识集
- Nginx配置文件详细说明
- java读取utf8类型的文件
- Google Guava官方教程(中文版)
- leetcode:Word Break
- 认识WebGL
- Map数量的修改-computeSplitSize
- AngularJS入门(四)
- 蛇形矩阵 和螺旋矩阵
- NGinx负载均衡策略
- AChartEngine中轮胎图
- 分工会的发挥个
- vs2012+cocos2dx 3.0 + cocostudio 1.4