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:

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:

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)

相关推荐

  1. 139. Word Break

    2023-12-05 17:20:13       54 阅读
  2. leetcode139-Word Break

    2023-12-05 17:20:13       5 阅读
  3. IOS面试题object-c 131-135

    2023-12-05 17:20:13       17 阅读
  4. 贪心算法03(leetcode1005,134,135

    2023-12-05 17:20:13       11 阅读
  5. Leetcode 139 单词拆分

    2023-12-05 17:20:13       28 阅读
  6. leetcode 139. 单词拆分

    2023-12-05 17:20:13       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 17:20:13       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 17:20:13       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 17:20:13       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 17:20:13       18 阅读

热门阅读

  1. HBase之HBCK2

    2023-12-05 17:20:13       45 阅读
  2. word表格图片批处理参考程序

    2023-12-05 17:20:13       36 阅读
  3. leetcode - 1268. Search Suggestions System

    2023-12-05 17:20:13       34 阅读
  4. 华为云购买参考:到底选购ECS还是CCE?

    2023-12-05 17:20:13       39 阅读
  5. POJ P1088动规的三种解法

    2023-12-05 17:20:13       45 阅读
  6. 简谈MySQL的binlog模式

    2023-12-05 17:20:13       38 阅读
  7. MySQL 表分区原理详解

    2023-12-05 17:20:13       42 阅读
  8. 【计算机网络】SSH文件传输协议

    2023-12-05 17:20:13       40 阅读