描述
给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得单词序列中所有的单词都是dict中的单词(序列可以包含一个或多个单词)。
例如:
给定s=“nowcode”;
dict=["now", "code"].
返回true,因为"nowcode"可以被分割成"now code".
思路:
在求F[8]的时候不需要关心F[1]~F[7]分割的是什么,只需拿结果。
代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& dict) {
if (s.empty())
return false;
if (dict.empty())
return false;
vector<bool> F(s.size() + 1, false);
// 初始化F(0) = true
F[0] = true;
for (int i = 1; i <= s.size(); ++i)
{
for (int j = i - 1; j >= 0; --j)
{
// F(i): true{j <i && F(j) && substr[j+1,i]能在词典中找到} OR false
// 第j+1个字符的索引为j
if (F[j] && dict.find(s.substr(j, i - j)) != dict.end())
{
F[i] = true;
break;
}
}
}
return F[s.size()];
}
};