Advertisement
1988coder

159. Longest Substring with At Most Two Distinct Characters

Dec 28th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. /**
  2.  * Sliding Window.
  3.  *
  4.  * Time Complexity: O(N)
  5.  *
  6.  * Space Complexity: O(1) - Map will max grow to size 3.
  7.  *
  8.  * N = length of the input string.
  9.  */
  10. class Solution {
  11.     public int lengthOfLongestSubstringTwoDistinct(String s) {
  12.         if (s == null) {
  13.             return 0;
  14.         }
  15.         if (s.length() <= 2) {
  16.             return s.length();
  17.         }
  18.  
  19.         Map<Character, Integer> map = new HashMap();
  20.  
  21.         int start = 0;
  22.         int end = 0;
  23.         int maxLen = 0;
  24.         int distinctCount = 0;
  25.  
  26.         while (end < s.length()) {
  27.             char endChar = s.charAt(end);
  28.             map.put(endChar, map.getOrDefault(endChar, 0) + 1);
  29.             if (map.get(endChar) == 1) {
  30.                 distinctCount++;
  31.             }
  32.             end++;
  33.             while (distinctCount > 2) {
  34.                 char startChar = s.charAt(start);
  35.                 map.put(startChar, map.get(startChar) - 1);
  36.                 if (map.get(startChar) == 0) {
  37.                     distinctCount--;
  38.                 }
  39.                 start++;
  40.             }
  41.             maxLen = Math.max(maxLen, end - start);
  42.         }
  43.  
  44.         return maxLen;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement