Leetcode练习(Python):动态规划类:第139题:单词拆分:给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

题目:

单词拆分:给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

  • 拆分时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。

思路:

动态规划常用思路。

程序:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        if not s:
            return False
        if not wordDict:
            return False
        length = len(s)
        auxiliary = [False for _ in range(length + 1)]
        auxiliary[0] = True
        for index1 in range(length):
            for index2 in range(index1 + 1, length + 1):
                if auxiliary[index1] == True and s[index1 : index2] in wordDict:
                    auxiliary[index2] = True
        result = auxiliary[-1]
        return result

  

原文地址:https://www.cnblogs.com/zhuozige/p/12884785.html