单词拆分(一)
https://www.lintcode.com/problem/107/?utm_source=sc-libao-ql
s = "lintcode"dict = ["lint", "code"]trues = "a"dict = ["a"]trueLast updated
https://www.lintcode.com/problem/107/?utm_source=sc-libao-ql
s = "lintcode"dict = ["lint", "code"]trues = "a"dict = ["a"]trueLast updated
from typing import (
Set,
)
class Solution:
"""
@param s: A string
@param word_set: A dictionary of words dict
@return: A boolean
"""
def word_break(self, s: str, word_set: Set[str]) -> bool:
# write your code here
if not s:
return True
n = len(s)
dp = [False] * (n+1)
dp[0] = True
max_len = max((len(word) for word in word_set), default=0) #注意字典为空 需要有默认值0
for i in range(1, n+1):
for j in range(max(0, i - max_len), i):#最长的词开始遍历 而不是每个字母都遍历,否则超时
if dp[j] and s[j:i] in word_set:
print(s[j:i])
dp[i] = True
break
#换成长度遍历更好想
```python
for i in range(1, n+1):
for l in range(0, max_len+1):#最长的词开始遍历 而不是每个字母都遍历,否则超时
if dp[i-l] and s[i-l:i] in word_set:
dp[i] = True
break
```
return dp[n]