算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 至多包含 K 个不同字符的最长子串,我们先来看题面:
https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/
Given a string, find the length of the longest substring T that contains at most k distinct characters.
定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。
示例
示例 1:
输入: s = "eceba", k = 2
输出: 3
解释: 则 T 为 "ece",所以长度为 3。
示例 2:
输入: s = "aa", k = 1
输出: 2
解释: 则 T 为 "aa",所以长度为 2。
解题
双指针,指针中间的是可能的答案。符合要求右指针向右扩,否则更新答案,左指针往右缩。
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int n = s.length();
if (n < k+1) return n;
int left = 0;
int right = 0;
//K-V:K是对应字符,V是最后一次出现的位置。
HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
int max_len = 0;
while (right < n) {
//符合要求就继续向右扩
if (hashmap.size() < k+1){
hashmap.put(s.charAt(right), right++);
}
if (hashmap.size() == k+1) {
int index = Collections.min(hashmap.values());
hashmap.remove(s.charAt(index));
left = index + 1;
}
max_len = Math.max(max_len, right - left);
}
return max_len;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode刷题实战325:和等于 k 的最长子数组长度