[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
原创粉丝点击