word break解题报告
来源:互联网 发布:怎样备份软件数据 编辑:程序博客网 时间:2024/05/29 13:09
Word Break
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".
https://leetcode.com/problems/word-break/
这道题问的是,有没有,不需要求完整的结果,所以用动态规划进行记录。
dp[i]表示0~i-1之间能不能被break。
dp[0]=true
dp[i]=true当且仅当存在k,i-1>=k>=0,dp[k]且i~k可以被break
解法如下:
class Solution {public: bool wordBreak(string s, unordered_set<string>& wordDict) { vector<bool> dp(s.size()+1,false); dp[0]=true; for(int i=0;i<s.size();i++){ for(int j=i;j>=0;j--){ if(dp[j]&&wordDict.count(s.substr(j,i-j+1))!=0){ dp[i+1]=true; break; } } } return dp[s.size()]; }};Word Break II
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"].
https://leetcode.com/problems/word-break-ii/
这是问具体结果的题,一般这种题要用DFS进行搜索,但是如果只用DFS那么时间复杂度太大,可以根据上一题,用上一题的条件进行剪枝,以减少时间复杂度。
class Solution {public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> res; vector<string> subres; vector<bool> posible(s.size()+1,false); posible[s.size()]=true; for(int i=s.size()-1;i>=0;i--){ for(int j=i;j<s.size();j++){ if(dict.count(s.substr(i,j-i+1))!=0&&posible[j+1]){ posible[i]=true; break; } } } findBreak(s,dict,res,subres,0,posible); return res; } void findBreak(string &s,unordered_set<string> &dict,vector<string> &res,vector<string> &subres,int start,vector<bool> &posible){ if(start==s.size()){ string temp=subres[0]; for(int i=1;i<subres.size();i++){ temp.append(" "+subres[i]); } res.push_back(temp); } for(int i=start;i<s.size();i++){ string piece=s.substr(start,i-start+1); if(dict.count(piece)!=0&&posible[i+1]){ subres.push_back(piece); findBreak(s,dict,res,subres,i+1,posible); subres.pop_back(); } } }};
- word break解题报告
- LeetCode Word Break 解题报告
- 【LeetCode】Word Break 解题报告
- [LeetCode]Word Break,解题报告
- Word Break [Leetcode解题报告]
- LeetCode — Word Break II 解题报告
- LeetCode — Word Break 解题报告
- LeetCode Word Break II 解题报告
- [LeetCode OJ] Word Break II 解题报告
- [LeetCode OJ] Word Break 解题报告
- 【LeetCode】Word Break II 解题报告
- [leetcode] 139. Word Break 解题报告
- [leetcode] 140. Word Break II 解题报告
- [Leetcode] 139. Word Break 解题报告
- [Leetcode] 140. Word Break II 解题报告
- Integer Break解题报告
- leetCode Word Break解题分享
- Word Pattern解题报告
- 常用英文翻译
- PHP面向对象_类型约束
- C++类的自动转换和强制转换详解和实现
- 常规类型的格式化
- android view的生命周期
- word break解题报告
- android studio 真机调试总是进入Debug模式的解决办法
- 编译nginx+rtmp排错
- 指定线程加入当前线程
- CMD 下使用java命令提示:找不到或无法加载主类
- 关于使用UDP实现多人聊天程序的Thinking
- oppo通知栏的那些事儿(如何分析系统级应用)
- velocity 输出格式化日期
- unity检测到某一物体不被特定的某一相机渲染