每天两道LeetCodeHard:(24)

126 阅读1分钟

140. Word Break II

拆分单词他又来了

题干:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.

解释:

给我们一个字符串,让我们拆分成字典中有的单词。条件是单词可以重复使用,而且字典中的单词不重复。

思考:

感觉这个题只能暴力dfs了,从每一个位置开始讨论是否切分,等于后面的结果。使用一个hashmap来去重

答案:

class Solution:
    def wordBreak(self, s: str, wordDict: list) -> list:
        if not s:
            return []
        _len, wordDict = len(s), set(wordDict)
        _min, _max = 2147483647, -2147483648
        for word in wordDict:
            _min = min(_min, len(word))
            _max = max(_max, len(word))

        def dfs(start):  # 返回s[start:]能由字典构成的所有句子
            if start not in memo:
                res = []
                for i in range(_min, min(_max, _len-start)+1):
                    if s[start: start+i] in wordDict:
                        res.extend(list(map(lambda x: s[start: start+i]+' '+x, dfs(start+i))))
                memo[start] = res
            return memo[start]

        memo = {_len: ['']}
        return list(map(lambda x: x[:-1], dfs(0)))

答案补充: