139. Word Break
Medium
2987164FavoriteShare
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because"leetcode"can be segmented as"leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because"applepenapple"can be segmented as"apple pen apple". Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false
Accepted
420,564
Submissions
1,124,919
这道题可以用记忆化和dp来做,这里用了dp算法,一开始要用hashset保存一下,dp[i]表示[0,i)字符串是否满足可以在hashset中找到对应的分割单词
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1);
dp[0] = true;
for (int i = 0; i < dp.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && wordSet.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp.back();
}
};
本文探讨了WordBreak问题的解决方法,通过使用动态规划(DP)算法,有效地判断一个字符串是否能被拆分为字典中的一系列单词。示例包括leetcode和applepenapple的成功案例,以及catsandog的失败案例。
1589

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



