Problem Description:
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"
.
这个题目最容易想到的是利用递归,不断地拆分出在字典中的单词,然后递归判断后缀是否能被拆分,后来想着利用利用字典中的单词最大最小长度提高效率,结果还是超时,具体代码如下:
class Solution {
public:
int minlen,maxlen;
void findlen(unordered_set<string> &dict)
{
unordered_set<string>::iterator iter=dict.begin();
minlen=(*iter).length();
maxlen=(*iter).length();
for(iter=dict.begin();iter!=dict.end();++iter)
{
if((*iter).length()<minlen)
minlen=(*iter).length();
if((*iter).length()>maxlen)
maxlen=(*iter).length();
}
}
bool wordcontain(string s, unordered_set<string> &dict,int begin)
{
if(begin==s.length())
return true;
for(int i=minlen;i<=maxlen;++i)
{
if((begin+i)>s.length())
continue;
if(dict.find(s.substr(begin,i))!=dict.end())
if(wordcontain(s,dict,begin+i))
return true;
}
return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty()||dict.empty())
return false;
findlen(dict);
return wordcontain(s,dict,0);
}
};
Submission Result: Time Limit Exceeded
然后在discuss区看了一些讨论,发现应该用动态规划来实现,利用一个一维bool数组记录子串是否可被拆分,减少了重复判断子串的次数,效率明显提高。
代码如下:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty()||dict.empty())
return false;
int len=s.size();
vector<bool> flag(len+1,false);
flag[len]=true;
for(int i=len-1;i>=0;--i)
for(int j=len;j>i;--j)
{
if(flag[j]&&dict.count(s.substr(i,j-i))==1)
{
flag[i]=true;
break;
}
}
return flag[0];
}
};