代码随想录算法训练营第四十九天| 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
  • s 和 wordDict[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);
    }
};
相关推荐
All for pursuit.5 小时前
【二叉树-10】114.二叉树展开为链表
数据结构·c++·算法·leetcode·链表
旖旎夜光6 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger6 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂6 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_106 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_36 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z6 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.6 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好6 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.6 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode