单词拆分II-LintCode
来源:互联网 发布:linux使用crontab-e 编辑:程序博客网 时间:2024/06/05 16:18
给一字串s和单词的字典dict,在字串中增加空格来构建一个句子,并且所有单词都来自字典。
返回所有有可能的句子。
样例:
给一字串lintcode,字典为[“de”, “ding”, “co”, “code”, “lint”]
则结果为[“lint code”, “lint co de”]。
第一次代码,TLE
#ifndef C582_H#define C582_H#include<iostream>#include<string>#include<vector>#include<unordered_set>#include<unordered_map>using namespace std;class Solution {public: /* * @param s: A string * @param wordDict: A set of words. * @return: All possible sentences. */ vector<string> wordBreak(string &s, unordered_set<string> &wordDict) { // write your code here vector<string> res; string str; findWord(s, wordDict, 1, str, res); for (auto &c : res) { c.pop_back(); } return res; } void findWord(string &s, unordered_set<string> &wordDict,int len,string &str,vector<string> &res) { if (s.size()==0) { res.push_back(str); } else { for (int i = len; i <= s.size(); ++i) { if (wordDict.find(s.substr(0, i)) != wordDict.end()) { string nstr = s.substr(i); string mstr = str; str += (s.substr(0, i) + " "); findWord(nstr, wordDict, 1, str, res); str = mstr; } } } }};#endif
利用isBreak(),预先判断是否可以拆分
#ifndef C582_H#define C582_H#include<iostream>#include<string>#include<vector>#include<unordered_set>#include <map> using namespace std;class Solution {public: /* * @param s: A string * @param wordDict: A set of words. * @return: All possible sentences. */ vector<string> wordBreak(string &s, unordered_set<string> &wordDict) { // write your code here vector<string> res; string str; if (isBreak(s,wordDict)) findWord(s, wordDict, 1, str,res); for (auto &c : res) { c.pop_back(); } return res; } void findWord(string &s, unordered_set<string> &wordDict,int len,string &str,vector<string> &res) { if (s.size()==0) { res.push_back(str); } else { for (int i = len; i <= s.size(); ++i) { if (wordDict.find(s.substr(0, i)) != wordDict.end()) { string nstr = s.substr(i); string mstr = str; str += (s.substr(0, i) + " "); findWord(nstr, wordDict, 1, str,res); str = mstr; } } } } bool isBreak(string &s, unordered_set<string> &wordDict) { int len = s.size(); vector<bool> dp(len + 1, false); dp[0] = true; for (int i = 1; i <= len; ++i) { for (int j = 0; j < i; ++j) { if (dp[j] && (wordDict.find(s.substr(j, i-j)) != wordDict.end())) { dp[i] = true; break; } } } return dp[len]; }};#endif
阅读全文
0 0
- 单词拆分II-LintCode
- 单词拆分 III-LintCode
- 单词拆分II
- LintCode 单词搜索 II
- LintCode : 单词搜索 II
- LintCode-单词接龙II
- 单词接龙 II-LintCode
- 单词搜索 II-LintCode
- LintCode 132-单词搜索II 深度优先
- Word Break II 求把字符串拆分为字典里的单词的所有方案 @LeetCode
- 单词拆分记忆
- 单词拆分 I
- LintCode 最长单词
- lintcode-单词搜索-123
- lintcode-单词接龙-120
- 最长单词(LintCode)
- LintCode- 单词切分
- lintcode ----最长单词
- 236. Lowest Common Ancestor of a Binary Tree
- 奶牛求幂 迭代加深搜索
- 《linux内核设计与实现-笔记2》
- 纯前端实现人脸识别-提取-合成
- redis基础、java集成Redis入门
- 单词拆分II-LintCode
- opencv(c++)-目录
- java中的final关键字
- Python学习---10
- 5.8字符
- 正则表达式第一弹
- linux学习第二十篇:zip压缩,tar打包以及打包压缩
- PC检测到是移动端进行页面转换
- K-均值聚类算法对未标注数据分组(1)