您的位置:首页 > 其它

Leetcode: Word Break

2013-10-06 03:50 393 查看
Given a string s and a dictionary of words dict, determine if s 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"
.

第一种方法:递归(超时)Time Limit Exceeded

思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配

Last executed input:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once.
if(s.length() < 1) return true;
bool flag = false;
for(int i = 1; i <= s.length(); i++)
{
string tmpstr = s.substr(0,i);
unordered_set<string>::iterator it = dict.find(tmpstr);
if(it != dict.end())
{
if(tmpstr.length() == s.length())return true;
flag = wordBreak(s.substr(i),dict);
}
if(flag)return true;
}
return false;
}


第二种方法:dpAccepted

思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配,在找后缀是否匹配时添加了记忆功能,如果当前的后缀没有匹配就把它放进set中,以后就不用再看这个后缀时候匹配了。

bool wordBreakHelper(string s, unordered_set<string> &dict,set<string> &unmatch) {
if(s.length() < 1) return true;
bool flag = false;
for(int i = 1; i <= s.length(); i++)
{
string prefixstr = s.substr(0,i);
unordered_set<string>::iterator it = dict.find(prefixstr);
if(it != dict.end())
{
string suffixstr = s.substr(i);
set<string>::iterator its = unmatch.find(suffixstr);
if(its != unmatch.end())continue;
else{
flag = wordBreakHelper(suffixstr,dict,unmatch);
if(flag) return true;
else unmatch.insert(suffixstr);
}
}
}
return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once.
int len = s.length();
if(len < 1) return true;
set<string> unmatch;
return wordBreakHelper(s,dict,unmatch);
}


题目刚放出来就A过了,好激动啊。。。

最近做题bug free的次数好多啊。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: