[LeetCode]Word Break
来源:互联网 发布:linux如何安装xz 编辑:程序博客网 时间:2024/06/01 22:55
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"
.
[LeetCode Source]
思路1:DFS暴力解决,搜索所有可能但是超时。
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s.size()==0) return false; return dfs(s,wordDict,""); } bool dfs(string s,unordered_set<string>& wordDict,string temp){ if(temp==s) return true; if(temp.size()>s.size()) return false; for(auto i=s.begin();i<s.end();++i){ if(dfs(s,wordDict,temp+*i)) return true; } return false; }};思路二:该题也可以采用动态规划解,效果好很多。写出状态转移方程。
F(i)表示字符串前i个字符是否可以wordbreak。
初始化F(0)=True,对于F(i)。
对所有小于i的j。
F(i) = F(j) + substr(i-j)(是否在Dict中),
如果有存在:F(i)=true.
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { vector<bool> F(s.length()+1,false); F[0]=true; for(int i=1;i<s.length()+1;++i) for(int j=0;j<i;++j){ if(F[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){ F[i] = true; } } return F[s.length()]; }};
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
- seven-things-you-should-known-about-ie-8
- Lua table函数库
- 陈怡暖:纪要助黄金逃过鬼门关,美数据开火或引波动
- Bitmap使用分享
- 数据库分区分库
- [LeetCode]Word Break
- android 实现摇一摇功能
- Java中int和Integer的区别
- 疯狂Java学习笔记(47)-----------泛型详解
- poj 2104 区间第K小 主席树入门题
- info.plist文件中各键的含义,留着用
- T3升级U8报错相关问题解决方案:
- Unity摄像机的使用四:望远镜的效果
- [转载]Z-stack 应用程序编程接口(API)-网络层