leetcode——139——Word Break
来源:互联网 发布:自贡广电网络 编辑:程序博客网 时间:2024/06/01 10:53
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"
.
这题可以用DFS做,但是更好的方法是使用DP,这种类型的DP感觉还是接触的稍微有些少。
题目中只要求源串分出来的词只要都在字典里就好,所以我们可以用dp[i] 表示源串的前i个字符可以满足分割,那么 dp[ j ] 满足分割的条件是存在k (0<=k<=j)使得 dp [k] && s[k+1,j]在字典里即可。注意下标问题,dp[i]是指前i个字符,对应的字母是s[i-1].
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { int len=s.length(); vector<int> dp(len+1,0); dp[0]=1; for(int i=1;i<=len;i++) { for(int j=i-1;j>=0;j--) { if(dp[j]==1&&wordDict.count(s.substr(j,i-j))) { dp[i]=1; break; } } } return dp[len]; }};
0 0
- **LeetCode—Word Break
- **LeetCode—Word Break
- LeetCode——Word Break
- LeetCode——Word Break
- LeetCode——Word Break
- leetcode——Word Break
- LeetCode——Word Break
- Leetcode—139. Word Break
- leetcode 139 —— Word Break
- Leetcode——139 Word Break && 140 Word BreakII
- LeetCode——Word Break II
- LeetCode OJ——Word Break
- Leetcode题解——Word Break
- LeetCode——139. Word Break
- LeetCode — Word Break II 解题报告
- LeetCode — Word Break 解题报告
- leetcode——139——Word Break
- LeetCode139—Word Break
- eclipse启动超时错误
- 奶牛xor--nkoi1873
- 专题三 第七题
- POJ - 1062 昂贵的聘礼(Dijkstra)
- Spring容器(四)
- leetcode——139——Word Break
- tableView注册cell的三种方式
- POJ - 1125 Stockbroker Grapevine(Floyd)
- Android面试题——ListView(一)
- Bootstrap 实现输入框中的 x 按钮删除文本值
- 例题9-1 UVA - 1025 A Spy in the Metro 城市里的间谍(DP)
- java中Iterator遍历时的删除问题
- MyBatis关联查询(一对一)
- MAC OS X10.10上Android开发环境搭建