当前位置: 首页> 新闻> 焦点 > 网站建设咨询费用_线上营销渠道有哪些_百度智能建站系统_推广电话

网站建设咨询费用_线上营销渠道有哪些_百度智能建站系统_推广电话

时间:2025/9/11 12:53:45来源:https://blog.csdn.net/codename_cys/article/details/146306894 浏览次数:1次
网站建设咨询费用_线上营销渠道有哪些_百度智能建站系统_推广电话
  • Leetcode 3485. Longest Common Prefix of K Strings After Removal
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3485. Longest Common Prefix of K Strings After Removal

1. 解题思路

这一题思路上我的一个直接的思路是使用trie树,然后每次通过增加和删除单词的方式维护当前的字典树,然后考察其中最长的至少出现过k次的prefix。

但是后来写作的时候发现其实已经没必要使用字典树了,用一个defaultdict记录一下各个prefix的频次即可。

2. 代码实现

给出python代码实现如下:

class Trie:def __init__(self, k):self.k = kself.cnt = defaultdict(int)self.valid = []def add_word(self, word):prefix = ""for c in word:prefix += cself.cnt[prefix] += 1if self.cnt[prefix] >= self.k:bisect.insort(self.valid, len(prefix))returndef del_word(self, word):prefix = ""for c in word:prefix += cself.cnt[prefix] -= 1if self.cnt[prefix] == self.k-1:self.valid.pop(bisect.bisect_left(self.valid, len(prefix)))returnclass Solution:def longestCommonPrefix(self, words: List[str], k: int) -> List[int]:n = len(words)if n <= k:return [0 for _ in words]trie = Trie(k)for word in words[1:]:trie.add_word(word)ans = [0 for _ in words]ans[0] = trie.valid[-1] if len(trie.valid) > 0 else 0for i in range(n-1):trie.add_word(words[i])trie.del_word(words[i+1])ans[i+1] = trie.valid[-1] if len(trie.valid) > 0 else 0return ans

提交代码评测得到:耗时5962ms,占用内存131.3MB。

关键字:网站建设咨询费用_线上营销渠道有哪些_百度智能建站系统_推广电话

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: