Word Break 单词分解
Word Break 单词分解
回溯
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def backtracking(idx):
if idx >= len(s):
return True
for w in wordDict:
if idx + len(w) <= len(s) and s[idx:idx+len(w)] == w and backtracking(idx + len(w)):
return True
return False
return backtracking(0)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
def backtracking(cur):
if cur == s:
return True
for w in wordDict:
if len(cur) + len(w) <= len(s) and s.find(cur + w) != -1 and backtracking(cur + w):
return True
return False
return backtracking('')
动态规划
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [True] + [False] * len(s)
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
"""
dp = [False] * len(s) + [True]
for i in range(len(s), -1, -1):
for j in range(i, len(s)+1):
if dp[j] and s[i:j] in wordDict:
dp[i] = True
break
return dp[0]
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号