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"
.
分析:
ac代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int i,j,L=s.length();
bool word[L+1];
for(i=1;i<=L;i++)
word[i]=false;
word[0]=true;
for(i=1;i<=L;i++)
{
for(j=i-1;j>=0;j--)
{
if(word[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end())
{
word[i]=true;
break;
}
}
}
return word[L];
}
};