mysql时间复杂度o1到on,139分词时间复杂度(O(n)),139WordBreak,On

时间复杂度(O(n))

通常情况下单词的最大长度是有限的,所以可以认为m为常量

最长的单词:Pneumonoultramicroscopicsilicovolcanoconiosis,长度=45

思想:动态规划

class Solution:

def wordBreak(self, s: str, wordDict: [str]) -> bool:

if len(s) == 0: return True

if len(wordDict) == 0: return False

words = set(wordDict)

max_len_word = max([len(w) for w in words])

res = [False] * len(s)

for i in range(len(s)):

if i > 0 and res[i - 1] != True: continue

for j in range(i + 1, min(len(s) + 1, i + max_len_word + 1)):

if s[i: j] in words:

res[j - 1] = True

return res[-1]

思想:前缀字典+动态规划(理论上,当数据量比较大的时候,效率更好)

class Solution:

def wordBreak(self, s: str, wordDict: [str]) -> bool:

if len(s) == 0: return True

pre_words = {}

for word in wordDict:#构建前缀字典

if word not in pre_words: pre_words[word] = [0, 1]

else: pre_words[word] = [pre_words[word][0], 1]

for j in range(1, len(word)):

if word[:j] not in pre_words: pre_words[word[:j]] = [1, 0]

else: pre_words[word[:j]] = [1, pre_words[word[:j]][1]]

res = [False] * len(s)

for i in range(len(s)):

if i > 0 and res[i - 1] != True: continue

for j in range(i + 1, len(s) + 1):

if s[i:j] not in pre_words: break

pre, e = pre_words[s[i:j]]

if e == 1: res[j - 1] = True

if pre == 0: break

return res[-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值