Leetcode-Word Break II
来源:互联网 发布:枪林弹雨免费刷枪软件 编辑:程序博客网 时间:2024/04/30 11:03
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].
A solution is [“cats and dog”, “cat sand dog”].
题意:对于一个字符串和给定字典,给出字符串由字典中字符组成的所有可能结果。
DP,类似前面提到的Work Break,这里标志位变为二维的,map< int,vector < string > > dp1,int存放字符在s中的位置,vector则存放改字符之前的所有可能string组合方式。
步骤:
对于s中(0,i)的字符串,判断是否在字典中,若在,则将其加入dp1[i]中,若不存在,则对j(j >= 1 && j < i),若dp1[j].size()>0,判断(j,i)之间的字符串是否在字典中,若存在,则将其附着在dp[j]中字符串之后。
vector<string> wordBreak(string s, unordered_set<string>& wordDict) { map<int,vector<string>> dp1; if(s.length()==0) { return vector<string>(); } int ii=s.length()-1; for(;ii>=0;--ii) { string t=s.substr(ii,s.length()-ii); if(wordDict.find(t)!=wordDict.end()) { break; } } if(ii<0) { return vector<string>(); } for(int i=1;i<=s.length();++i) { string t=s.substr(0,i); dp1[i]=vector<string>(); if(wordDict.find(t)!=wordDict.end()) { dp1[i].push_back(t); } for(int j=1;j<i;++j) { if(dp1[j].size()>0) { string t1=s.substr(j,i-j); if(wordDict.find(t1)!=wordDict.end()) { for(int k=0;k<dp1[j].size();++k) { string t3=dp1[j][k]; t3=t3+" "+t1; dp1[i].push_back(t3); } } } } } return dp1[s.length()]; }
0 0
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Leetcode: Word Break II
- LeetCode Word Break II
- Word Break II leetcode
- [leetcode]Word Break II
- leetcode -- word break II
- CSS透明度设置支持IE,Chrome,Firefox浏览器
- Java回调机制
- java学习笔记 i++和++i
- 前端基础知识整理(二)
- ubuntu apt
- Leetcode-Word Break II
- Java获取项目路径下的方法(全)
- leetcode-223 Rectangle Area
- 安装程序无法创建 DCOM 用户帐户以注册 \valec.exe
- 【iOS开发系列】版本新特性界面
- leetcode Contains Duplicate II 哈希表
- 均匀设计表的构造+考虑子目标偏好度的均匀设计
- ViewPager滑动和点击切换内容
- 二分查找求解equal_range区间