139. Word Break

139. Word Break

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

DP:

python 复制代码
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        wordSet = set(wordDict)
        n = len(s)
        dp = [False] * (n + 1)  # dp[i] 表示字符串的前 i 个字符是否可以被拆分成单词
        dp[0] = True  # 初始状态,空字符串可以被拆分成单词

        for i in range(1, n + 1): # 遍历背包
            for j in range(i): # 遍历单词
                if dp[j] and s[j:i] in wordSet:
                    dp[i] = True  # 如果 s[0:j] 可以被拆分成单词,并且 s[j:i] 在单词集合中存在,则 s[0:i] 可以被拆分成单词
                    break

        return dp[n]

backtracking:

python 复制代码
class Solution:
    def backtracking(self, s: str, wordSet: set[str], startIndex: int) -> bool:
        # 边界情况:已经遍历到字符串末尾,返回True
        if startIndex >= len(s):
            return True

        # 遍历所有可能的拆分位置
        for i in range(startIndex, len(s)):
            word = s[startIndex:i + 1]  # 截取子串
            if word in wordSet and self.backtracking(s, wordSet, i + 1):
                # 如果截取的子串在字典中,并且后续部分也可以被拆分成单词,返回True
                return True

        # 无法进行有效拆分,返回False
        return False

    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        wordSet = set(wordDict)  # 转换为哈希集合,提高查找效率
        return self.backtracking(s, wordSet, 0)
相关推荐
gc_22996 小时前
学习C#调用OpenXml操作word文档的基本用法(34:学习图形类-4)
word·openxml·anchor·浮动式布局
yuhulkjv3357 小时前
腾讯元宝公式粘贴word乱码
人工智能·chatgpt·word·deepseek·ai导出鸭
hef2881 天前
Java读取Word图片坐标的两种方法
java·开发语言·word
OEC小胖胖1 天前
ChatGPT导出Word怎么做?Chat2File 安装与使用教程
chatgpt·word·效率工具·ai工具·浏览器扩展
庖丁AI1 天前
合同比对工具怎么选?Word、PDF 和扫描件差异对比思路
pdf·word
你挚爱的强哥1 天前
【样式问题】将当前word所有文字样式、字体、字号大小 全局设置为以后任何一个新的空白文档都共享使用
word
luoyayun3611 天前
基于 DOCX 模板书签替换的 Word 文档生成方案,解决跨平台Word输出问题
word·qt word·linux word
包子源1 天前
PDF 转 Word/Excel 全链路实战:Next.js + 阿里云文档智能
pdf·word·excel
tedcloud1232 天前
academic-research-skills部署教程:构建AI辅助科研环境
服务器·人工智能·word·excel·dreamweaver
AI一天,人间一年2 天前
word删除指定页面
word