版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89738621
Given a non-empty string s and a dictionary wordDictcontaining 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
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false
题目大意:
给出一个字符串和一个字典,要求从字典当中查询出word来组合成目标s。
解题思路:
我们看到下面的两个函数,将字符串分成两个部分,递归判断这两部分在字典中是否有对应word。
str.substr(a)--截取str里面从a开始之后的字符组成的字符串
str.substr(a,b) --截取str里面从a开始之后的字符长度为b的字符串
class Solution {
private:
unordered_map<string, int> m;
unordered_map<string, bool> dp;
public:
bool wordBreak(string s, vector<string>& wordDict) {
for(auto x: wordDict) m[x]++;
return DFS(s);
}
bool DFS(string s){
if(dp.count(s)) return dp[s];
if(s.empty()) return true;
bool found=false;
for(int i=1;i<=s.size() && !found;i++){
if(m.count(s.substr(0,i))) found |= DFS(s.substr(i));
}
dp[s] = found;
return dp[s];
}
};