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)
相关推荐
CodeCraft Studio1 天前
国产化Excel处理控件Spire.XLS教程:如何使用 Java 将 TXT 文本转换为 Excel 表格
java·word·excel·spire·文档格式转换·txt转excel
开开心心就好2 天前
电子报纸离线保存:一键下载多报PDF工具
网络·笔记·macos·pdf·word·音视频·phpstorm
书中自有妍如玉2 天前
Node.Js 实现模板生成Word、Word转Pdf文件、Excel生成、上传和下载
pdf·node.js·word
格兰芬多呼神护卫3 天前
python实现Latex格式的公式转OMML并写入word
python·c#·word
不坑老师4 天前
利用不坑盒子在WPS中插入网页,放映的电脑无需安装插件,直接就能显示网页!
microsoft·word·powerpoint·wps
ljh_learn_from_base4 天前
【spring boot 使用apache poi 生成和处理word 文档】
java·spring boot·word·apache
2501_920955574 天前
Word崩溃打不开?实测三款Word文档修复工具!
word
乘风!5 天前
前端Jquery,后端Java实现预览Word、Excel、PPT,pdf等文档
pdf·word·excel·jquery
程序员小羊!5 天前
Flink(用Scala版本写Word Count 出现假报错情况解决方案)假报错,一直显示红色报错
flink·word·scala
Eiceblue5 天前
React 前端实现 Word(Doc/Docx)转 HTML
前端·react.js·word