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)
相关推荐
GEEKVIP3 小时前
如何在 Windows 10 上恢复未保存/删除的 Word 文档
macos·ios·智能手机·电脑·word·笔记本电脑·iphone
不写八个20 小时前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
GEEKVIP1 天前
如何修复变砖的手机并恢复丢失的数据
macos·ios·智能手机·word·手机·笔记本电脑·iphone
ChinaDragonDreamer3 天前
Word:表格公式计算
word
ziyue75753 天前
java将word转pdf
java·pdf·word
fxybg20223 天前
探索高效免费的PDF转Word工具,开启便捷办公之旅
人工智能·自然语言处理·pdf·word·机器翻译
几度热忱3 天前
【word脚注】双栏设置word脚注,脚注仅位于左栏,右栏不留白
word·脚注
奇客软件4 天前
如何在 macOS(MacBook Pro、Air 和 iMac)上恢复未保存的 Word 文档
android·windows·macos·智能手机·word·笔记本电脑·iphone
GEEKVIP4 天前
如何在 Windows PC 或笔记本电脑上恢复未保存的 Word 文档
windows·macos·ios·智能手机·word·cocoa·iphone
三木一立4 天前
Word导出样式模板,应用到其他所有word
word