给定一个非空字符串 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
法一:回溯法 DFS搜索
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# 回溯法
def back_trace(start,s,wordDict):
'''
以start为第一个字母 暴力匹配 dfs
'''
if start>len(s)-1:return True
for end in range(start,len(s)):
sub_str=s[start:end+1]
if sub_str in wordDict:
flag=back_trace(end+1,s,wordDict)
if flag:return True
return False
return back_trace(0,s,wordDict)
法二:dp
注意:
dp[i]=(dp[j] and s[i+1:j+1] in wordDict) dp[i]表示以i为分割点,能否得到字典中的词,j为上一次的分割点
这里j要遍历i以前的所有可分割点 即dp[j]=True的点 可先求出字典中的单词的最大长度进行剪枝优化
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# 动态规划
# dp[i]=(dp[j] and s[i+1:j+1] in wordDict) dp[i]表示以i为分割点,能否得到字典中的词,j为上一次的分割点
if not s or not wordDict:return False
n=len(s)
dp=[False]*(n)
# 优化 先找到字典中单词的最大长度
max_len=max(map(len,wordDict))
for i in range(n):
# 在最大长度内遍历即可
start=max(-1,i-max_len)
for j in range(start,i+1):
if j==-1 or dp[j]==True:
if s[j+1:i+1] in wordDict:
dp[i]=True
break
return dp[-1]