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".
Subscribe to see which companies asked this question
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int len = s.length();
if(len == 0) return true;
if(wordDict.empty()) return false;
vector<int> dp(len, 0);
for(int i = 0; i < len; i++) {
for(int j = i; j >= 0; j--) {
string str = s.substr(j, i-j+1);
if(wordDict.find(str)!=wordDict.end()) {
if(j <= 0) dp[i] = 1;
else if(dp[j-1] == 1) {
dp[i] = 1;
break;
}
}
}
}
return dp[len-1];
}
};
本文探讨了一个经典的字符串问题:如何判断一个字符串能否通过字典中的单词进行分割。通过使用动态规划方法,文章提供了一种高效的解决方案。
1588

被折叠的 条评论
为什么被折叠?



