1988coder

340. Longest Substring with At Most K Distinct Characters

Dec 28th, 2018
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. /**
  2.  * Sliding Window
  3.  *
  4.  * Time Complexity : O(N) - Each character is added and removed once.
  5.  *
  6.  * Space Complexity: O(k) - Map can grow to size k+1
  7.  *
  8.  * N = length of input string s
  9.  *
  10.  * Proof of Time Complexity:
  11.  *
  12.  * Suppose there are M distinct chars in input string, each char is repeating j
  13.  * times on average. Thus total number of chars = M * j = N. Thus number of
  14.  * operations:
  15.  *
  16.  * 1) To add into map = N,
  17.  *
  18.  * 2) M-k chars will be removed from map. thus (M-k)*j remove operations are
  19.  * performed.
  20.  *
  21.  * Thus total operations = N + (M-k)*j. Here k is very small, thus total
  22.  * operations = 2*N
  23.  */
  24. class Solution {
  25.     public int lengthOfLongestSubstringKDistinct(String s, int k) {
  26.         if (s == null || k <= 0) {
  27.             return 0;
  28.         }
  29.         if (s.length() <= k) {
  30.             return s.length();
  31.         }
  32.  
  33.         Map<Character, Integer> map = new HashMap();
  34.  
  35.         int start = 0;
  36.         int end = 0;
  37.         int maxLen = 0;
  38.         int distinctCount = 0;
  39.  
  40.         while (end < s.length()) {
  41.             char endChar = s.charAt(end);
  42.             map.put(endChar, map.getOrDefault(endChar, 0) + 1);
  43.             if (map.get(endChar) == 1) {
  44.                 distinctCount++;
  45.             }
  46.             end++;
  47.  
  48.             while (distinctCount > k) {
  49.                 char startChar = s.charAt(start);
  50.                 map.put(startChar, map.get(startChar) - 1);
  51.                 if (map.get(startChar) == 0) {
  52.                     distinctCount--;
  53.                 }
  54.                 start++;
  55.             }
  56.  
  57.             maxLen = Math.max(maxLen, end - start);
  58.         }
  59.  
  60.         return maxLen;
  61.     }
  62. }
Add Comment
Please, Sign In to add comment