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;
}
}
分类:
LeetCode
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库