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)
相关推荐
Tmin.13 小时前
Word论文中遇到的
word
智航GIS1 天前
9.4 Word 自动化
python·自动化·word
深念Y1 天前
学习通下载老师没有开放下载的文档的方法
学习·pdf·word·文档·下载·学习通·开发者模式
开开心心_Every2 天前
提取PPT/Word/Excel图片工具
数据库·微信·pdf·word·powerpoint·excel·语音识别
蜡笔小鑫jolly2 天前
在WORD中插入表格后放图片一直不吻合怎么办?
word
YuQiao03032 天前
华科学位论文——驯服word公式编辑器(不是mathtype的)
编辑器·word
YuQiao03032 天前
华科学位论文——驯服word之 目录
word
重生之光头强下海当程序猿2 天前
word将所选内容超链接为文章其他内容
word
SEO-狼术3 天前
Convert Word Documents to PDF
pdf·word
发际线的忧伤3 天前
Word 的一个显示模式,页眉页脚数据丢失?
word