题目描述
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".
分析:
动态规划,设f(0,i)是指字符串s从0到i的子串能否分割。那么有状态转移方程:f(i)=f(j)&&f(j+1,i)
代码:
//代码是牛客网的代码 leetcode题目太多了不知道从何刷起 就打算先刷牛客了
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
bool *table = new bool[s.size()+1];
for(int i=1;i<s.size()+1;++i)
table[i]=0;
table[0] = true;
for(int i=1;i<=s.size();++i)
{
for(int j = 0;j<i;++j)
{
if(table[i])
break;
table[i] = (table[j]&&dict.find(s.substr(j,i-j))!=dict.end());
}
}
return table[s.size()];
}
};