题目
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]
解题思路
思路和单词拆分几乎一样,不同点在于:
- 当找到符合规则的子串后,不能直接退出,而要找完所有true的前子串才行
- 把原先的true_list改为true_dict,键的规则没变,值是以键的位置结束对应的所有子串
因为改变了上述1,所以有个用例是无法通过的:
“aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”
[“a”,“aa”,“aaa”,“aaaa”,“aaaaa”,“aaaaaa”,“aaaaaaa”,“aaaaaaaa”,“aaaaaaaaa”,“aaaaaaaaaa”]
这里我查了官方题解,似乎也没有什么巧思,只能针对这个用例,先判断可行性(wordDict set是否为string set的超集)再做了
时间复杂度没有变化,最坏情况下仍然为 o ( n 2 ) o(n^2) o(n2)
代码
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
dict_set = set()
for item in wordDict:
dict_set.update(set(item))
if not dict_set.issuperset(set(s)):
return []
true_dict = {0: [[]]}
for end_index in range(1, len(s) + 1):
cur_indexs = list(true_dict.keys())[::-1]
for begin_index in cur_indexs:
if s[begin_index: end_index] in wordDict:
if end_index in true_dict:
true_dict[end_index].extend([item + [s[begin_index:end_index]] for item in true_dict[begin_index]])
else:
true_dict[end_index] = [item + [s[begin_index:end_index]] for item in true_dict[begin_index]]
return [' '.join(item) for item in true_dict.get(len(s), [])]