给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
样例
给出
s = "lintcode"
dict = ["lint","code"]
返回 true 因为"lintcode"可以被空格切分成"lint code"
点题:不断地优化提前返回
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
if (s.size() == 0) {
return true;
}
if (dict.size() == 0) {
return false;
}
// above two condition, i have some different opinion
int max_len = 0;
for (string str:dict) {
if (str.size() > max_len) {
max_len = str.size();
}
}
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for (int i = 1; i <= s.size(); i++) {
for (int j = i - 1; j >= 0; j--) {
if (i - j > max_len) {
break;
}
if (dp[j] == 0) {
continue;
}
string str = s.substr(j, i - j);
if (dict.find(str)!= dict.end()) {
dp[i] = 1;
break;
}
}
}
return dp[s.size()] == 1;
}
};