LeetCode || Word Break
来源:互联网 发布:淘宝客php源码下载 编辑:程序博客网 时间:2024/05/18 06:26
Word Break
Total Accepted: 15419 Total Submissions: 75670My SubmissionsGiven 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"
.
即给定一个字符串s,词典dict,判断s能否由dict中的词构成。开始时想到的方法是,遍历dict中的词,然后判断其在s中是否存在,如果存在就将该词替换为空串,最终看s是否变为空串,这种方法是错误的,比如 s=“dogs”,dict=[ "gs", "s", "dog" ],判断的时候会首先剔除s中的gs,剩下do,显然判断为false。
正确的方法是使用动态规划,定义一个bool数组dp[ len ],len为字符串长度,递推方程为:dp[ i ] = dict.find( s.substr( 0, i+1 )) OR (dp[ j ] && dict.find(s.substr( j+1, i-j )));
即dp[ i ] 的值为true,等价于子串(0,i)是dict的一个词或者存在j<i ,使得dp[ j ] 为真并且子串(j,i)也在dict出现;
代码如下:
class Solution {public: bool wordBreak(string s, unordered_set<string> &dict) { int len = s.length(); if(len<1) return true; bool *dp = new bool[len]; memset(dp, false, len); for(int i = 0; i<len; ++i){ if(dict.find(s.substr(0, i+1)) != dict.end()) dp[i] = true; else{ for(int j=0; j<i; ++j){ if(dp[j] && dict.find(s.substr(j+1, i-j)) != dict.end()){ dp[i]=true; break; } } } } return dp[len-1]; }};
该方法的时间复杂度应该是 O(len^2 * logX),其中X为dict的长度,len为字符串s的长度。logX为在dict中find一个子串的时间(如果dict用树实现的话)。
- 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
- oracle 冷备份脚本
- 跨平台
- 组织行为学对项目管理的意义(2):人格的大五模型 .
- HDU 4336 Card Collector(动态规划-概率DP)
- MIT--FaceDatabase
- LeetCode || Word Break
- 组织行为学对项目管理的意义:动机理论 .
- Java Enum枚举
- 自定义控件 imageview 双击显示红色边框
- LeetCode:Combinations
- Android 自动更新(模拟服务器)
- 多线程编程4 - GCD
- 【新手入门】mathematica 画图
- foreach遍历输出数据表