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"
可以使用动态规划求解:
设dp[i]为以第i个字符结尾时,从0开始的字符串是否能匹配到字典
则有动态转移方程: dp[i]= true s[0:i]可以在字典中找到
true dp[k]=true && s[k+1:i]可以在字典中找到 0<=k<i
false 其他
bool wordBreak(string s, unordered_set<string> &dict) {
int length = s.length();
if (s.empty())
return false;
bool* dp = new bool[length];
memset(dp, 0, length * sizeof(bool));
for (int i = 0; i < length; ++i)
{
if (dict.find(s.substr(0,i+1)) != dict.end())
{
dp[i] = true;
continue;
}
for (int j = 0; j < i; ++j)
{
if (dp[j] == true && dict.find(s.substr( j+1 , i-j)) != dict.end())
{
dp[i] = true;
}
}
}
return dp[length - 1];
}