Word Break II
来源:互联网 发布:软件bs架构 编辑:程序博客网 时间:2024/06/10 04:49
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完以后得到dp数组,然后根据dp数组构造可能的sentence即可。
class Solution {public: int len=0; vector<string> v; bool* f; vector<string> wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once and is reused by each test case. word(s,dict); if(!f[s.length()]) return v; build(s,s.length(),"",dict); return v; } void build(string s,int index,string cur,unordered_set<string> &dict){ if(index==0){ v.push_back(cur.substr(0,cur.length()-1)); return; } for(int i=1;i<=len && index-i>=0;i++){ if(find(s.substr(index-i,i),dict) && f[index-i]){ build(s,index-i,s.substr(index-i,i)+" "+cur,dict); } } } bool find(string s,unordered_set<string> &dict){ unordered_set<string>::iterator it = dict.find(s); return it!=dict.end(); } void word(string s, unordered_set<string> &dict) { string str; for(unordered_set<string>::iterator it = dict.begin();it!=dict.end();it++){ str = *it; len = max((int)str.length(),len); } f = new bool[s.length()+1]; f[0] = true; for(int i=0;i<s.length();i++){ for(int j=1;i+1-j>=0 && j<=len;j++){ f[i+1] = f[i+1-j] && find(s.substr(i+1-j,j),dict); if(f[i+1]) break; } } } };
0 0
- Word Break && Word Break II
- Word Break && Word Break II
- [leetcode]Word Break II
- Word Break II
- Word Break II
- LeetCode:Word Break II
- Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- Word Break II
- Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- Word Break II
- Word Break II
- [LeetCode] Convert Sorted Array to Binary Search Tree
- Hibernate 数据库到实体类
- DataGridView单击选中一整行,只能单选,不能选择多行,只能选择一行
- unity开发 --------- c# 基本语法 002
- 用友NC6该产品的用户数已达到产品授权数!
- Word Break II
- Python序列化的使用(有少量修改)
- 谷歌在招什么样的人?
- 线性表之顺序存储结构删除操作
- form外观控制
- SQL Server 2012 安装图解教程
- ip转换为基本类型的简单封装
- hadoop 单机 伪分布式 完全分布式 区别
- media and camera 框架之二: MediaRouter