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)
相关推荐
一川风絮千片雪12 小时前
【排版教程】如何在Word/WPS中优雅的插入参考文献
word·wps
杜大哥12 小时前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
青涩小鱼14 小时前
在WPS中设置word的页码不从第一页开始,从指定页开始插入页码
word·wps
企鹅侠客1 天前
开源免费文档翻译工具 可支持pdf、word、excel、ppt
人工智能·pdf·word·excel·自动翻译
hello_simon2 天前
【Word转PDF】在线Doc/Docx转换为PDF格式 免费在线转换 功能强大好用
职场和发展·pdf·word·学习方法·word转pdf·石墨文档·word转换
有限无限资料库3 天前
VBA脚本将DeepSeek嵌入Word中教程
开发语言·c#·word
嘿嘿潶黑黑4 天前
python 快速实现链接转 word 文档
python·word
hello_simon4 天前
pdf转换成word在线 简单好用 支持批量转换 效率高 100%还原
性能优化·pdf·产品运营·word·pdf转换·自媒体·pdf转word
bu_shuo4 天前
Word中样式的管理
word·样式复制
猿大师办公助手4 天前
Weboffice在线Word权限控制:限制编辑,只读、修订、禁止复制等
vue.js·chrome·microsoft·word