题目:
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 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
思路:
首先,回溯可以得到正确答案,但是会超时。考虑空间换时间的动态规划。
设数组dp[i]
表示长度为i的单词s[0:i]
是否可以被拆分,推导其转移方程。
求解dp[i]
时,我们需要枚举dp[0]
至dp[i-1]
中为True
的位置,即可以被划分的位置j
,然后判断s[j:i]
是否在字典中,若在,则这是一个可以被拆分的子串。转移方程如下:
dp[i] = dp[j] and (s[j:i] in wordDict)
代码:动态规划
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[len(s)]
代码:回溯
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def dfs(s):
if not s:
return True
res = False
for i in range(len(s)):
if s[0:i+1] in wordDict:
res = dfs(s[i+1:]) or res
return res
return dfs(s)