139.单词拆分
dp, https://leetcode.cn/problems/word-break/
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
注意,你可以重复使用字典中的单词。示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false提示:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s和wordDict[i]仅由小写英文字母组成wordDict中的所有字符串 互不相同
python
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
dp = [False] * (n + 1)
dp[0] = True # 空字符串可以被表示
for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[n]python
from typing import List
from functools import lru_cache
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@lru_cache(None)
def dfs(x):
if len(x) == 0:
return True
for i in range(1, len(x)+1):
if x[0:i] in wordDict and dfs(x[i:]):
return True
return False
return dfs(s)
if __name__ == "__main__":
s = "leetcode"
wordDict = ["leet", "code"]
print(Solution().wordBreak(s, wordDict)) # True
# s = "applepenapple"
# wordDict = ["apple", "pen"]
# print(Solution().wordBreak(s, wordDict)) # True
#
# s = "catsandog"
# wordDict = ["cats", "dog", "sand", "and", "cat"]
# print(Solution().wordBreak(s, wordDict)) # Falsepython
from typing import List
from functools import cache
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# 作者:灵茶山艾府
# https://leetcode.cn/problems/word-break/solutions/2968135/jiao-ni-yi-bu-bu-si-kao-dpcong-ji-yi-hua-chrs/
max_len = max(map(len, wordDict)) # 用于限制下面 j 的循环次数
words = set(wordDict) # 便于快速判断 s[j:i] in words
@cache # 缓存装饰器,避免重复计算 dfs 的结果(记忆化)
def dfs(i: int) -> bool:
if i == 0: # 成功拆分!
return True
return any(s[j:i] in words and dfs(j)
for j in range(i - 1, max(i - max_len - 1, -1), -1))
return dfs(len(s))
if __name__ == "__main__":
sol = Solution()
print(sol.wordBreak("leetcode", ["leet", "code"])) # True
print(sol.wordBreak("applepenapple", ["apple", "pen"])) # True
print(sol.wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"])) # False
print(sol.wordBreak("cars", ["car", "ca", "rs"])) # True