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

Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II

  • Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3306. Count of Substrings Containing Every Vowel and K Consonants II

1. 解题思路

这一题的话思路上就是一个滑动窗口,考察没一个点作为起始位置时,满足同时包含5个元音字符以及恰好 k k k个辅音字符的第一个位置,然后从该位置到其下一个辅音字符之间的任意一个位置都可以构成一个满足条件的substring。

因此,我们只需要控制这样一个滑动窗口并提前计算出一下每一个位置对应的下一个辅音字符出现的位置即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def countOfSubstrings(self, word: str, k: int) -> int:
        n = len(word)
        
        next_consonants = [n for _ in range(n)]
        idx = n
        for i in range(n-1, -1, -1):
            next_consonants[i] = idx
            if word[i] not in "aeiou":
                idx = i
        
        i, j = 0, 0
        cnt = defaultdict(int)
        ans = 0
        while j < n:
            while j < n and (any(cnt[ch] <= 0 for ch in "aeiou") or cnt["c"] < k):
                if word[j] in "aeiou":
                    cnt[word[j]] += 1
                else:
                    cnt["c"] += 1
                j += 1
            
            while all(cnt[ch] > 0 for ch in "aeiou") and cnt["c"] >= k:
                if cnt["c"] == k and all(cnt[ch] > 0 for ch in "aeiou"):
                    ans += (next_consonants[j-1] - (j-1))
                if word[i] in "aeiou":
                    cnt[word[i]] -= 1
                else:
                    cnt["c"] -= 1
                i += 1
        return ans

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

相关文章:

  • 针对考研的C语言学习(定制化快速掌握重点2)
  • Zabbix 7.0 图表中文乱码问题处理步骤
  • u2net网络模型训练自己数据集
  • 【Linux】包管理器、vim详解及简单配置
  • 9月27日,每日信息差
  • MATLAB案例 | 沪深股市收益率的二元Copula模型
  • sql中的regexp与like区别
  • 三位数排序
  • PDF对话RAG应用开发实战
  • grafana加载缓慢解决方案
  • MySQL数据库备份详解
  • 内存泄漏和内存溢出简述
  • 9、论文阅读:无监督的感知驱动深水下图像增强
  • Modbus协议和PLC协议的区别和联系
  • 丹摩智算平台部署 Llama 3.1:实践与体验
  • R语言Shiny包新手教程
  • 11-pg内核之锁管理器(六)死锁检测
  • 【解决方案】git错误:对象文件为空 error: object file
  • vincent,一个超酷的Python库
  • 详解Linux文件系统
  • 巴基斯坦外长:近期军事回应是自卫措施
  • 妻子藏匿一岁幼儿一年多不让丈夫见,法院发出人格权侵害禁令
  • 中消协点名新能源汽车行业:定金退款争议频发
  • 中国驻美国大使馆发言人就中美经贸高层会谈答记者问
  • 陈丹燕:赤龙含珠
  • 联想发布超级智能体矩阵,杨元庆:美国关税影响反映在产品定价上,未来不确定性很大