leetcode340. 至多包含 K 个不同字符的最长子串

给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。

示例 1:

输入: s = "eceba", k = 2
输出: 3
解释: 则 T 为 "ece",所以长度为 3。
示例 2:

输入: s = "aa", k = 1
输出: 2
解释: 则 T 为 "aa",所以长度为 2。

思路:双指针,指针中间的是可能的答案。符合要求右指针向右扩,否则更新答案,左指针往右缩。

leetcode159. 至多包含两个不同字符的最长子串

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 hashmap = new HashMap();
 
    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)