解题思路:
利用深度优先搜索可以解决这道题,但是简单的直接用深度优先搜索会导致时间超过限制;所以我们对每一个位置进行一次遍历即可,在每一个位置依次检测是否能到达即可。
具体代码如下:
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if s in wordDict:
return True
index_set = [False]*(len(s) + 1)
index_set[0] = True
for i in range(1, len(s) + 1): # i [1, 8]
for idx in range(i): # idx [0, 7]
if index_set[i] == False and index_set[idx] and s[idx:i] in wordDict:
index_set[i] = True
return index_set[-1]