【Leetcode】Word Break II
来源:互联网 发布:农业大数据方案 编辑:程序博客网 时间:2024/05/21 17:47
【题目】
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"]
.
class Solution {public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> vResult; vResult.clear(); int len=s.length(); if((0==len)||(0==dict.size()))return vResult; bool dp[len+1]; vector<vector<string> >strArr; strArr.clear(); memset(dp,false,sizeof(dp)); for(int i=0;i<=len;++i){ vector<string> v; v.clear(); strArr.push_back(v); } dp[len]=true; for(int i=(len-1);i>=0;--i){ vector<string> vec; vec.clear(); for(unordered_set<string>::iterator it=dict.begin();it!=dict.end();++it){ int size=(*it).length(); if(((i+size)<=len)&&dp[i+size]&&((*it)==s.substr(i,size))){ dp[i]=true; if((i+size)==len){ vec.push_back(*it); continue; } if(strArr[i+size].size()>0){ for(int j=0;j<strArr[i+size].size();++j){ if(strArr[i+size][j]!="")vec.push_back((*it)+" "+strArr[i+size][j]); } } } } if(vec.size()>0)strArr[i]=vec; } vResult=strArr[0]; return vResult; }};
【总结】
1.使用动态规划,和word break题一样,区别是要这次要记录下中间结果,以备需要时取。这里使用vector<vector<string> >保存。
2.思路是:从后往前扫描目标字符串s,记录下每个位置dp[i]值,如果s[i...len]可以用dict中的词表达,值为TRUE,否则为FALSE;同时vector<vector<string> >保存s[i...len]能用dict的单词表达的方式。扫描到s首字母的结果就是题目所需。
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
- 常用排序算法总结与分析(含全部源码)
- OCP 1Z0 052 11
- Remove Duplicates from Sorted Array II
- 一种对拉格朗日乘子的直观理解
- leedcode做题总结,题目Reverse Words in a String14/03/05
- 【Leetcode】Word Break II
- 黑马程序员-Java基础语法
- 黑马程序员-Java关键字
- oracle11g倒出空表
- HDU 3049 Data Processing 数论题解
- 黑马程序员_XML
- SharePoint Survey WebPart 调查 Web部件
- Windows (R) Installer.
- 黑马程序员-Java实现多线程的两种方式