139. Word Break
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
Approach
- 题目大意就是wordDict中的字符串是否可以组成s,可以重复使用。虽然这道题是动态规划题,但自己还是忍不住暴力解,一开始构造字典树来解,可是题目要求的是整个字符串而不是序列,那么字典树就有点慢了,我又开始改造成unordered_set哈希表存字符串,速度明显提升,但是还是斗不过恶心的数据,所以还是要用动态规划来解,但是这里我用记忆化搜索会更通俗易懂,这里我把字符串的每个位置当做一个状态记录下来,从这个状态出发,看是否能匹配完成,然后记录下来,当下次又走到这个状态下,就可以直接返回,这些就是记忆化搜索的核心。
Code
class Solution {
public:
int DFS(string &s, int n, int pos, unordered_set<string> &unst,vector<int> &cache) {
if (pos == n)return 1;
if (cache[pos] != 0)return cache[pos];
for (int i = 1; i <=n-pos; i++) {
string substr = s.substr(pos, i);
if (unst.find(substr)!=unst.end()) {
cache[pos]=DFS(s, n, pos + i, unst, cache);
if (cache[pos] == 1)return 1;
}
}
return -1;
}
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string>unst;
for (string &word : wordDict) {
unst.insert(word);
}
vector<int>cache(s.size(), 0);
return DFS(s, s.size(), 0, unst, cache)==1;
}
};