0395. Longest Substring with At Least K Repeating Characters (M)

Longest Substring with At Least K Repeating Characters (M)

题目

Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is less than or equal to k.

Example 1:

Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input: s = "ababbc", k = 2
Output: 5
Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of only lowercase English letters.
  • 1 <= k <= 10^5

题意

在指定字符串中找到一个最长的子串,使其包含的每个字母出现的次数都大于等于一个阈值。

思路

求子串问题一般都会想到滑动窗口,但因为本题是要求超过阈值,直接用滑动窗口很难想出一个用来判断该缩短还是伸长窗口的标准。官方解答提供了一个很巧妙的思路:一个子串能拥有的不同字符的种类是受原字符串限制的,所以可以将窗口变动的依据定为“当前子串拥有的不同字符的个数”,这样最多进行26次遍历即可得到答案。


代码实现

Java

class Solution {
    public int longestSubstring(String s, int k) {
        int ans = 0;
        int uniqueCount = 0;
        boolean[] exist = new boolean[26];

        for (char c : s.toCharArray()) {
            if (!exist[c - 'a']) {
                exist[c - 'a'] = true;
                uniqueCount++;
            }
        }

        for (int ceil = 1; ceil <= uniqueCount; ceil++) {
            int unique = 0, satisfied = 0, start = 0, end = 0;
            int[] count = new int[26];

            while (end < s.length()) {
                if (unique <= ceil) {
                    int index = s.charAt(end) - 'a';
                    if (count[index] == 0) unique++;
                    count[index]++;
                    if (count[index] == k) satisfied++;
                    end++;
                } else {
                    int index = s.charAt(start) - 'a';
                    if (count[index] == k) satisfied--;
                    count[index]--;
                    if (count[index] == 0) unique--;
                    start++;
                }

                if (unique == ceil && unique == satisfied) {
                    ans = Math.max(ans, end - start);
                }
            }
        }
        
        return ans;
    }
}
posted @   墨云黑  阅读(108)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
点击右上角即可分享
微信分享提示