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)
相关推荐
骆驼爱记录5 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
2301_816997885 天前
Word 清除格式的方法
word
微光feng6 天前
毕业论文word引用操作汇总
word·目录·公式·毕业论文·交叉引用·题注
2301_816997886 天前
Word 功能区与快速访问工具栏
word
halen3336 天前
Hellowordl: The Masters Tool for Word Puzzle Enthusiasts
word
lpfasd1236 天前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
Cxiaomu6 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
bu_shuo6 天前
Word中插入文本内容控件并交叉引用
word·内容控件
缺点内向6 天前
C#中如何创建目录(TOC):使用Spire.Doc for .NET实现Word TOC自动化
c#·自动化·word·.net
2301_816997886 天前
Word 创建打开与保存文档
c#·word·xhtml