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
題意:判斷給出的字符串是否可以被 wordDict
中的字符串拼湊出來。
思路:動態規劃的典型題目。
代碼:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wd(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
//dp[i]表示s的前i個字符可以被wordDict拼湊出來
//dp[0]即s的前0個字符"", 爲true
dp[0] = true;
//每次循環, 檢查長度爲i的字符串區間是否可以被拼湊出來,直到檢查整個s
for (int i = 1; i <= s.size(); ++i) {
//每次循環, 若前面長j的字符串可以被拼出來, 則檢查從j開始的長i區間
//的後一部分長爲i-j的字符串是否可以在wordDict中找到
//接着依次檢查長爲j+1,j+2,...,i-1的字符串是否可以被拼出來,...
for (int j = 0; j < i; ++j) {
if (dp[j] && wd.find(s.substr(j, i - j)) != wd.end()) {
//前面的長j字符串和後面長i-j的字符串均可拼出
//則s的前i個字符都可拼湊, dp[i]爲true
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};