博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Word Break II
阅读量:4071 次
发布时间:2019-05-25

本文共 1314 字,大约阅读时间需要 4 分钟。

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"].

继续熟悉dfs。

class Solution {public:    void dfs(string s, int start, vector
& re, string &cur_re, unordered_set
&dict){ if(start < 0) return; int len = s.length(); //from back to front for(int i = start; i >= 0; --i){ string sub = s.substr(i, start - i + 1); if(dict.find(sub) != dict.end()){ int len = cur_re.length(); cur_re.insert(0, " "+sub); dfs(s, i - 1, re, cur_re, dict); //恢复先前的内容,便于回退 cur_re = cur_re.substr(cur_re.length() - len); } } if(dict.find(s.substr(0, start + 1)) != dict.end()){ cur_re.insert(0, s.substr(0, start + 1)); re.push_back(cur_re); } } vector
wordBreak(string s, unordered_set
&dict) { vector
re; string cur_re; dfs(s, s.length() - 1, re, cur_re, dict); return re; }};
更多dfs和leetcoded参见

转载地址:http://srlji.baihongyu.com/

你可能感兴趣的文章
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>
OS + UNIX AIX command
查看>>
OS + UNIX AIX performance
查看>>
OS + UNIX AIX Tools
查看>>
my ReadBook_liutongjingjixue / circulation economics
查看>>
my ReadBook_wangluoyingxiaoyucehua / network marketing / wangluoyingxiao
查看>>
db base database
查看>>
Spring2.5+MINA2搭建Socket Server
查看>>
jcharts画线图,饼图和柱状图
查看>>
监控服务器端口,Down掉会自动重启,并发送邮件 Linux Shell
查看>>
Git提交错误:RPC failed; result=22, HTTP code = 411
查看>>
Druid使用ConfigFilter
查看>>
Elicpse使用技巧-打开选中文件文件夹或者包的当前目录
查看>>
eclips 运行项目内存不足的解决方案
查看>>
linux 挂载盘阵 smb
查看>>
漫谈 JAVA程序员、架构师、项目经理
查看>>
ceph (luminous 版) crushmap 与 pool结合用于物理划分 IO 使用域
查看>>
mysql 相关索引
查看>>
tomcat7 - cacti 备忘
查看>>
kubernetes 上部署 kubevirt 运行虚拟机
查看>>