139、单词拆分
动态规划法,状态意为某处字符之前到它自身的头部是否为True.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
size=len(s)
dic={word for word in wordDict}
dp=[False for _ in range(size)]
dp[0]=s[0] in dic
for i in range(1,size):
if s[:i+1] in dic:
dp[i]=True
continue
for j in range(i):
if dp[j] and s[j+1:i+1] in dic:
dp[i]=True
break
return dp[-1]
140、单词拆分II
递归(较难理解,QAQ我尽力了~~)
放张图理解一下:
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict)
mem = {}
return self.helper(s, wordDict, mem)
def helper(self, key, wordDict, mem):
if key in mem:
return mem[key] #返回键值对 s: s.value
value = [] #res是个临时变量,代表截至此处的可能的句子
if not key:
value.append("")
return value #最后从这儿出来
for i in range(len(key)+1):
if key[:i] in wordDict: #若前尾巴是字典中的某个词
sublist = self.helper(key[i:], wordDict, mem)
for it in sublist:
value.append(key[:i] + ('' if not it else ' ') + it) #这么写是因为可能遍历到很后面了,it为''
mem[key] = value #在mem中新添键值对 s:res
return value