Advertisement
uopspop

Untitled

Jul 10th, 2021
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. class Solution {
  2.     public int lengthOfLongestSubstringKDistinct(String s, int k) {
  3.          
  4.         int len_max = 0;
  5.         int count_k = 0;
  6.         int i_left = 0;
  7.         int i_right = -1;
  8.        
  9.         // int[] char_count = new int[26];
  10.         Map<Character, Integer> char_count = new HashMap<>();
  11.        
  12.         while (true) {
  13.             if (i_left == s.length()) break;
  14.            
  15.             if (count_k <= k) {
  16.                 // found one possible answer
  17.                 int len_now = i_right - i_left + 1;
  18.                 len_max = Math.max(len_max, len_now);
  19.                
  20.                 // still have room to grow length
  21.                 i_right++;
  22.                 if (i_right == s.length()) break;
  23.                
  24.                 char c_now = s.charAt(i_right);
  25.                 // int i_now = c_now - 'a'; // all char is lower-case?
  26.                 if (char_count.get(c_now) == null || char_count.get(c_now) == 0) {
  27.                     // a new char inserted
  28.                     char_count.put(c_now, 0);
  29.                     count_k++;
  30.                 }
  31.                 char_count.put(c_now, char_count.get(c_now) + 1);
  32.                                
  33.             }else {
  34.                 // one k too much, try to reduce it
  35.                
  36.                 char c_now = s.charAt(i_left);
  37.                 char_count.put(c_now, char_count.get(c_now) - 1);
  38.                 if (char_count.get(c_now) == 0) {
  39.                     // the last char here is removed
  40.                     count_k--;
  41.                 }
  42.                 i_left++;
  43.             }
  44.            
  45.         }
  46.        
  47.         return len_max;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement