[leetcode] Word Break
来源:互联网 发布:淘宝pc端是在哪里 编辑:程序博客网 时间:2024/05/22 12:26
Given a string s and a dictionary of words dict, determine ifs 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".
思路,直接进行递归超时了,然后就添加了一个set保存中间结果
输入示例:
leetcode
2
leet
code
代码如下:
#include<iostream>#include<unordered_set>#include<string>using namespace std;bool word(string s,unordered_set<string> &dict,unordered_set<string> &temp){ int len=s.size(); string tmp; tmp.clear(); if(dict.find(s)!=dict.end()){ return true; } for(int i=1;i<len+1;i++){ tmp=s.substr(0,i); if(dict.find(tmp)!=dict.end()){ if(temp.find(s.substr(i))!=temp.end()){ continue; }else{ if(word(s.substr(i),dict,temp)){ return true; }else{ temp.insert(s.substr(i+1)); } } } } return false;}bool wordBreak(string s, unordered_set<string> &dict){ int len=s.size(); if(len<1) return true; unordered_set<string> temp; return word(s,dict,temp);}int main(){ string s; cin>>s; int n; cin>>n; string a; unordered_set<string> dict; dict.clear(); for(int i=0;i<n;i++){ cin>>a; dict.insert(a); } bool res; res=wordBreak(s,dict); if(res){ cout<<"true"<<endl; }else{ cout<<"false"<<endl; }}
0 0
- leetcode Word Break & Word Break ||
- Leetcode: Word Break
- [leetcode]Word Break
- [leetcode]Word Break II
- LeetCode:Word Break
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break
- [LeetCode] Word Break II
- LeetCode: Word Break
- leetcode之Word Break
- [LeetCode]Word Break II
- [LeetCode]Word Break
- leetcode-Word Break
- LeetCode 之 Word Break
- leetcode word break
- LeetCode | Word Break
- LeetCode | Word Break II
- 大矮子灰 烧纸灰 商会 用酒
- 指定浏览某浏览器
- VMware Workstation环境下安装增强工具
- hdu 不容易系列之(3)―― LELE的RPG难题
- ZOJ_3686_A Simple Tree Problem(线段树成端更新)
- [leetcode] Word Break
- cas入门之二十:cas审计日志Inspektr(下)
- java Fork-join框架
- iOS开发之Objective-C与JavaScript的交互
- 搜索题集
- 1612: [Usaco2008 Jan]Cow Contest奶牛的比赛 (Floyd)
- 光盘启动 (Boot from CDROM) Part 1- SakiProject
- Eddy's digital Roots
- thinkphp3.2 验证码生成和点击刷新验证码