当前位置: 首页 > news >正文

Leetcode 3485. Longest Common Prefix of K Strings After Removal

  • 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 = k
        self.cnt = defaultdict(int)
        self.valid = []
    
    def add_word(self, word):
        prefix = ""
        for c in word:
            prefix += c
            self.cnt[prefix] += 1
            if self.cnt[prefix] >= self.k:
                bisect.insort(self.valid, len(prefix))
        return
        
    def del_word(self, word):
        prefix = ""
        for c in word:
            prefix += c
            self.cnt[prefix] -= 1
            if self.cnt[prefix] == self.k-1:
                self.valid.pop(bisect.bisect_left(self.valid, len(prefix)))
        return

class 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 0
        for 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 0
        return ans

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

相关文章:

  • 较为完善的搜索函数
  • LangChain 动态任务分发:开启大模型任务流的巅峰之术(三)
  • CRMEB标准版/开源版商城系统【遇坑解决】
  • 3.5 二分查找专题:LeetCode 852. 山脉数组的峰值
  • 单片机自学总结
  • 如何搭建一个安全经济适用的TRS交易平台?
  • Linkreate wordpressAI插件 24小时自动生成原创图文,新增从百度、必应搜索引擎自动获取相关下拉关键词
  • SpringBoot第三站(4):配置嵌入式服务器使用外置的Servlet容器
  • LeetCode56☞合并区间
  • 超参数优化算法:scikit-opt库、Scikit-Optimize库
  • GPU视频编解码:X86 VideoProcessFrame 视频编解码入门(二)
  • Git提交前时间检查
  • Golang | 每日一练 (6)
  • Mysql 安装指南(小白入门)
  • 基于FPGA轨道交通6U机箱CPCI脉冲板板卡
  • vs2017版本与arcgis10.1的ArcObject SDK for .NET兼容配置终结解决方案
  • 【笔记】计算机网络——数据链路层
  • 10.PE导出表
  • 3.8 Spring Boot监控:Actuator+Prometheus+Grafana可视化
  • 【vue2 + Cesium】使用Cesium、添加第三方地图、去掉商标、Cesium基础配置、地图放大缩小事件、获取可视区域、层级、高度
  • 北大深圳研究生院成立科学智能学院:培养交叉复合型人才
  • 央行副行长:增强外汇市场韧性,坚决对市场顺周期行为进行纠偏
  • 加拿大温哥华一车辆冲撞人群,造成多人伤亡
  • 葛兰西的三位一体:重提并复兴欧洲共产主义的平民圣人
  • 三杀皇马剑指四冠,硬扛到底的巴萨,赢球又赢人
  • 知名计算机专家、浙江大学教授张森逝世