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".
Have you been asked this question in an interview?
此题相当简单,动态规划
- bool wordBreak(string s, unordered_set<string> &dict) {
- int len=s.length();
- vector<bool> dp(len+1,false);
- dp[0]=true;
- for(int i=0;i<=len;i++){
- for(int j=0;j<i;j++){
- if(dict.find(s.substr(j,i-j))!=dict.end() && dp[j]==true){
- dp[i]=true;
- }
- }
- }
- return dp[len];
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(1) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文介绍了一种利用动态规划解决LeetCode上的单词拆分问题的方法。给定一个字符串和一个字典,判断该字符串是否可以被拆分成字典中存在的单词序列。
342

被折叠的 条评论
为什么被折叠?



