139. 单词拆分
题目描述
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
方法1:DFS
- 未优化版,会超时
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
lenth = len(s)
def dfs(start):
if start >= lenth:
return True
for i in range(start + 1, lenth + 1):
if s[start:i] in wordDict:
if dfs(i):
return True
return False
return dfs(0)
- 优化版:使用记忆的方式减少回溯
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# dfs 增加记忆优化
lenth = len(s)
memo = {}
hashset = set(wordDict)
def dfs(start):
if start >= lenth:
return True
# 记忆已经访问过的字符,避免多次深入回溯
if start in memo:
return memo[start]
for i in range(start + 1, lenth + 1):
if s[start:i] in hashset and dfs(i):
memo[start] = True
return True
memo[start] = False
return False
return dfs(0)
方法2:动态规划
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# DP, [0,j][j, i]
lenth = len(s)
hashset = set()
for word in wordDict:
hashset.add(word)
dp = [False] * (lenth + 1) # dp[i]表示[0, i]是否在wordList里
dp[0] = True # 边界处理
for i in range(1, lenth + 1):
for j in range(i, -1, -1):
if dp[j] and s[j: i] in hashset:
dp[i] = True
break
return dp[lenth]

浙公网安备 33010602011771号