题目要求:
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"
.
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { int len = s.size(); vector<bool> dp(len + 1, false); dp[0] = true; for (size_t i = 1; i <= len; ++i) { for (int j = i -1; j >= 0; --j) { if(dp[j]) { string sub = s.substr(j, i - j); if(dict.count(sub) != 0) { dp[i] = true; break; } } } } return dp[len]; } };