"""
给定一个非空字符串 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
"""
# 自己写的,超时
def wordBreak(s, wordDict):
word = set(wordDict)
lens = len(wordDict)
def helper(s, wordDict):
for i in range(lens):
length = len(wordDict[i])
if len(s[:length]) > 0:
if s[:length] in word:
match = helper(s[length:], wordDict)
if match == False:
continue
else:
return True
else:
return True
return False
return helper(s, wordDict)
def wordBreak1(s, wordDict):
return word_Break(s, set(wordDict), 0)
def word_Break(s, wordDict, start):
if start == len(s):
return True
for end in range(start+1, len(s)+1):
if s[start:end] in wordDict and word_Break(s, wordDict, end):
return True
return False
def wordBreak2(s, wordDict):
n = len(s)
if not wordDict:
return not s
dp = [False] * (n+1)
dp[0] = True
for i in range(1, n+1):
for j in range(i-1, -1, -1):
if dp[j] and s[j:i] in wordDict:
dp[i] =True
break
return dp[-1]
def wordBreak3(s, wordDict):
wordDict = set(wordDict)
if not wordDict:
return not s
max_len = max(map(len, wordDict))
def helper(s):
if not s:
return True
for i in range(len(s)):
if i < max_len and s[:i+1] in wordDict and helper(s[i+1:]):
return True
return False
return helper(s)
139_单词拆分
最新推荐文章于 2024-02-26 12:54:01 发布