代码随想录算法训练营第四十九天| 139.单词拆分

代码随想录算法训练营第四十九天| 139.单词拆分


### 文章目录

  • [代码随想录算法训练营第四十九天| 139.单词拆分](#文章目录 代码随想录算法训练营第四十九天| 139.单词拆分 @[toc] 139.单词拆分)
  • [@[toc]](#文章目录 代码随想录算法训练营第四十九天| 139.单词拆分 @[toc] 139.单词拆分)
  • [139.单词拆分](#文章目录 代码随想录算法训练营第四十九天| 139.单词拆分 @[toc] 139.单词拆分)

139.单词拆分

题目链接:139. 单词拆分 - 力扣(LeetCode)

题目描述:

给你一个字符串 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 中的所有字符串 互不相同
cpp 复制代码
class Solution {
public:
    bool InS (const std::string& s,const std::unordered_set<std::string>& wordSet,std::vector<bool>& memory,int startIndex) {
        if (startIndex >= s.size()) {
            return true;
        }
        // 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果
        if (!memory[startIndex]) return memory[startIndex];
        for (int i = startIndex; i < s.size(); i++) {
            std::string word = s.substr(startIndex, i - startIndex + 1);
            if (wordSet.find(word) != wordSet.end() && InS(s, wordSet, memory, i + 1)) {
                return true;
            }
        }
        memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的
        return false;
    }
    bool wordBreak(std::string s, std::vector<std::string>& wordDict) {
        std::unordered_set<std::string> wordSet(wordDict.begin(), wordDict.end());
        std::vector<bool> memory(s.size(), 1); // -1 表示初始化状态
        return InS(s, wordSet, memory, 0);
    }
};
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
元亓亓亓2 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
仙俊红2 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌3 天前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
爱编程的化学家3 天前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
吃着火锅x唱着歌3 天前
LeetCode 1446.连续字符
算法·leetcode·职场和发展
愚润求学3 天前
【贪心算法】day10
c++·算法·leetcode·贪心算法