139. 单词拆分

139. 单词拆分

给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s

注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。

示例 1:

输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。

示例 2:

输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
     注意,你可以重复使用字典中的单词。

示例 3:

输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false

提示:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • swordDict[i] 仅有小写英文字母组成
  • wordDict 中的所有字符串 互不相同

思路:

​ 如果求出wordDict是否能拼出S,即求S从0...开始能否匹配,求S从0开始能否匹配,如果找到一个匹配,就转化为从i开始能否匹配。因此是一个的动态规划,同时可以发现存在重叠子问题,使用备忘录解决。

class Solution {
public:
    vector<int>memo;
    bool wordBreak(string s, vector<string>& wordDict) {
        memo.resize(s.size(),-1);
        return dp(s,0,wordDict);//定义:s的0到...能否被拼凑出
    }
    bool dp(string s,int i,vector<string>& wordDict){
        //base case
        if(i==s.size())return true;//匹配完s
        //备忘录未记录
        if(memo[i]!=-1)return memo[i]==1?true:false;
        
        //可以重复使用 每次都可以遍历所有单词
        for(string word:wordDict){
            int l=word.length();
            if(i+l>s.length())continue;//如果加上当前字符串长度超过s则不可能选
            string subS="";
            for(int j=i;j<i+l;j++)subS+=s[j];
            if(subS!=word){//如果s的i~i+len不能和当前字符匹配
                continue;
            }
            //如果可以匹配i~i+len
            if(dp(s,i+l,wordDict)){
                memo[i]=1;
                return true;
            }
        }
        //无法匹配
        memo[i]=0;
        return false;
    }
};
posted @ 2022-06-03 09:51  BailanZ  阅读(48)  评论(0编辑  收藏  举报