Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int lengthOfLongestSubstringKDistinct(String s, int k) {
- int len_max = 0;
- int count_k = 0;
- int i_left = 0;
- int i_right = -1;
- // int[] char_count = new int[26];
- Map<Character, Integer> char_count = new HashMap<>();
- while (true) {
- if (i_left == s.length()) break;
- if (count_k <= k) {
- // found one possible answer
- int len_now = i_right - i_left + 1;
- len_max = Math.max(len_max, len_now);
- // still have room to grow length
- i_right++;
- if (i_right == s.length()) break;
- char c_now = s.charAt(i_right);
- // int i_now = c_now - 'a'; // all char is lower-case?
- if (char_count.get(c_now) == null || char_count.get(c_now) == 0) {
- // a new char inserted
- char_count.put(c_now, 0);
- count_k++;
- }
- char_count.put(c_now, char_count.get(c_now) + 1);
- }else {
- // one k too much, try to reduce it
- char c_now = s.charAt(i_left);
- char_count.put(c_now, char_count.get(c_now) - 1);
- if (char_count.get(c_now) == 0) {
- // the last char here is removed
- count_k--;
- }
- i_left++;
- }
- }
- return len_max;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement