题目描述
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”.
分析
>设数组大小为N;初始化一个数组dp得
vector<bool> dp(N+1,false);
dp[i]表示为字符串s[0...i-1]位置,能否由字典中的词组成,则dp[len]则为最终的解
代码如下
void isWordBreak(string &s,unordered_set<string> &dict, vector<bool> &dp)
{
for (unsigned long i = 1; i <= s.size(); ++i){
for (int j = i - 1; j >= 0; --j){
if(dp[j]&&dict.find(s.substr(j,i-j))!=dict.end())
dp[i]=true;
}
}
}
bool wordBreak(string&s, unordered_set<string> &dict)
{
const int N = s.size();
vector<bool> dp(N + 1, false);
dp[0] = true;
isWordBreak(s, dict, dp);
return dp[N];
}