单词拆分

Category Difficulty Likes Dislikes
algorithms Medium (52.29%) 1433 -

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

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

示例 1:

  1. 输入: s = "leetcode", wordDict = ["leet", "code"]
  2. 输出: true
  3. 解释: 返回 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 中的所有字符串 互不相同

题解:

class Solution {
public:
//这个dp[i]比较新鲜,是true或者false,i表示字符串长度
//初始化dp[0]是true,因为需要有true才能传导下去
//排列数先背包
    bool wordBreak(string s, vector<string>& wordDict) {
        //改成unorde_set一个是去重,一个是为了可以查找
        unordered_set<string>word(wordDict.begin(),wordDict.end());
        vector<bool> dp(s.size()+1,false);
        dp[0]=true;
        for (int i = 1; i <= s.size(); i++) //先背包
        {
            for (int j = 0; j <i; j++)  //物品,这里的遍历物品其实并不是拿出set中的物品,是得到已经起始位置以及个数
            {
                //遍历的不是set中的物品,而是剩余组成i的字符
                string str=s.substr(j,i-j); //(从j包括j开始,i-j个字符组成的中间字符)
                if(word.find(str) != word.end()&&dp[j]==true) dp[i]=true;
            }
        }
        return dp[s.size()];
    }
};

class Solution {
public:
//这个dp[i]比较新鲜,是true或者false,i表示字符串长度
//初始化dp[0]是true,因为需要有true才能传导下去
//组合数先物品
    bool wordBreak(string s, vector<string>& wordDict) {
        //改成unorde_set一个是去重,一个是为了可以查找
        unordered_set<string>word(wordDict.begin(),wordDict.end());
        vector<bool> dp(s.size()+1,false);
        dp[0]=true;
        for (int i = 0; i < s.size(); i++) //物品 ,注意这里的i的意义,是一个起始坐标
        {
            for (int j = 1; j <= s.size(); j++) //背包
            {
                string str=s.substr(i,j-i);
                if(i<=j&&word.find(str)!=word.end()&&dp[i]==true)dp[j]=true;
            }
        }
        return dp[s.size()];
    }
};