[Leetcode]Word Break
2015-11-08 16:30
351 查看
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 =
dict =
Return true because
class Solution {
public:
/*algorithm: DFS + hash
*/
bool dfs(string &s,int start,unordered_set<string>& wordDict,unordered_set<string>& unmatched)
{
if(start == s.size())return true;
for(int l = s.size()-start;l >= 1;l--){
string word = s.substr(start,l);
if(wordDict.count(word)){
if(unmatched.count(s.substr(start+l)))continue;//add this,otherwise TME
if(dfs(s,start+l,wordDict,unmatched)){
return true;
}
}else{
if(!unmatched.count(word))
unmatched.insert(word);
}
}
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
unordered_set<string> dict;
return dfs(s,0,wordDict,dict);
}
};
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:
/*algorithm: DFS + hash
*/
bool dfs(string &s,int start,unordered_set<string>& wordDict,unordered_set<string>& unmatched)
{
if(start == s.size())return true;
for(int l = s.size()-start;l >= 1;l--){
string word = s.substr(start,l);
if(wordDict.count(word)){
if(unmatched.count(s.substr(start+l)))continue;//add this,otherwise TME
if(dfs(s,start+l,wordDict,unmatched)){
return true;
}
}else{
if(!unmatched.count(word))
unmatched.insert(word);
}
}
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
unordered_set<string> dict;
return dfs(s,0,wordDict,dict);
}
};
class Solution { public: /*algorihtm dp(i,j): define substr(i,j) can word break dp(0,n) = 1 if dp(0,i) and dp(i+1,n) can word break */ bool wordBreak(string s, unordered_set<string>& wordDict) { int n = s.size(); vector<vector<int> >dp(n,vector<int>(n,0)); for(int i = 0;i < n;i++){ for(int j = i;j < n;j++){ string word = s.substr(i,j-i+1); if(wordDict.count(word)){ dp[i][j]=1; if(dp[0][i-1])dp[0][j]=1; } } } return dp[0][n-1]; } };
相关文章推荐
- 各种排序总结(二)之--归并排序、希尔排序、插入排序
- 安卓开发常用工具类和第三方框架
- ios提交代码到远程仓库
- 多图技术贴:深入浅出解析大数据平台架构
- Backbone系列:todo的demo
- soj 3596 Article Decryption(trie树 + dp)
- HDU3635 Dragon Balls
- HDU3635 Dragon Balls
- 拍照、偷拍
- 僵尸网络的相关研究文章
- arm交叉编译器gnueabi、none-eabi、arm-eabi、gnueabihf、gnueabi区别
- Android笔记(五十四) Android四大组件之一——ContentProvider(一)
- 蓝桥杯练手之数字游戏
- 最大乘积(Maximum Product,UVA 11059)
- 并查集
- ubuntu java6 install
- 为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?
- excel2013选中框颜色怎么改
- 【Android】Android工具函数整理
- 复制对象