139. Word Break
class Solution:
def concatenate_DFS(self, wordDict, x, vis):
if x == len(self.s):
return True
vis[x] = True
for word in wordDict:
if self.s[x:x+len(word)]==word and not vis[x+len(word)]:
if self.concatenate_DFS(wordDict, x+len(word), vis):
return True
return False
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
self.s = s
vis = [False] * (len(s)+1)
return self.concatenate_DFS(wordDict, 0, vis)
本文介绍了一个名为WordBreak的问题的解决方案,使用深度优先搜索(DFS)策略,通过检查给定字符串`s`是否可以由词典中的单词通过连接得到。函数`concatenate_DFS`递归地遍历并判断子串是否在词典中,同时记录已访问状态。
137





