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实现,暂时先放一放,DP总觉得比较难。
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
//i represent length of substr
for (int i = 1; i < s.size(); i++)
{
string word = s.substr(0, i);
if (dict.count(word) != 0)
{
if (wordBreak(s.substr(i+1), dict))
return true;
}
}
return false;
}
};