首页 > 代码库 > 139. Word Break
139. Word Break
#139. Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
##分析##
定义 d[i]表示 0~i子串是否能通过dict中元素表示
如果存在{str(j,i)∈ dict | j<i } 则d[i]=true
##代码##
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict)
{
unordered_set<string> dict;
for(int i = 0; i < wordDict.size(); i++)
{
dict.insert(wordDict[i]);
}
size_t len = s.size();
vector<int> d(len+1, false);
d[0] = true;
for(int i = 1; i < len+1; i++)
for(int j=i-1;j>=0;j--)
{
if(d[j] && dict.find(s.substr(j,i-j)) != dict.end())
{
d[i] = true;
break;
}
}
return d[len];
}
};
139. Word Break