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


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


    139.单词拆分

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

    题目描述:

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

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

    示例 1:

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

    示例 2:

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

    示例 3:

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

    提示:

    • 1 <= s.length <= 300
    • 1 <= wordDict.length <= 1000
    • 1 <= wordDict[i].length <= 20
    • swordDict[i] 仅由小写英文字母组成
    • wordDict 中的所有字符串 互不相同
    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);
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    33.Mybatis-Plus
    AtCoder Beginner Contest 275(C,E 补)
    跨境电商独立站COD建站
    SpringMVC 环境配置
    MPLS-LDP(个人学习笔记)
    Spark读取CSV文件(Scala)
    uniapp微信小程序-项目实战修改密码
    C++ list的模拟实现
    2023年显著性检测论文及代码汇总(3)
    C#开发的OpenRA游戏之世界存在的属性GivesExperience(4)
  • 原文地址:https://blog.csdn.net/qq_33909269/article/details/133754950