给定字符串 s 和单词字典 dict,确定 s 是否可以分成一个或多个以空格分隔的子串,并且这些子串都在字典中存在。
样例
样例 1:
输入: "lintcode", ["lint", "code"]
输出: true
样例 2:
输入: "a", ["a"]
输出: true
class Solution {
public:
/*
* @param s: A string
* @param dict: A dictionary of words dict
* @return: A boolean
*/
bool wordBreak(string &s, unordered_set<string> &dict) {
// write your code here
int len = s.size();
vector<bool> dp(len + 1, false);
dp[0] = true;
for (int i = 0; i < len + 1; ++i) {
for (int j = 0; j < i; ++j)
{
if (!dp[j]) continue;
if (dict.find(s.substr(j, i - j)) != dict.end())
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
};