Question
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".
Solution
用动态规划求解,遍历所有长度,看当前长度i是否可以完全分化。 长度为i的字符串分为两部分,前一部分是已经算过的是否可以划分的,只需要在字典中找后面一部分是否存在。
时间复杂度为O(n^2),空间复杂度为O(n).
Code
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
vector<bool> dp(s.length() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j <= i; j++) {
if (dp[j]) {
string str = s.substr(j, i - j);
if (dict.find(str) != dict.end()) {
dp[i] = true;
break;
}
}
}
}
return dp[s.length()];
}
};