Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Sliding Window.
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1) - Map will max grow to size 3.
- *
- * N = length of the input string.
- */
- class Solution {
- public int lengthOfLongestSubstringTwoDistinct(String s) {
- if (s == null) {
- return 0;
- }
- if (s.length() <= 2) {
- return s.length();
- }
- Map<Character, Integer> map = new HashMap();
- int start = 0;
- int end = 0;
- int maxLen = 0;
- int distinctCount = 0;
- while (end < s.length()) {
- char endChar = s.charAt(end);
- map.put(endChar, map.getOrDefault(endChar, 0) + 1);
- if (map.get(endChar) == 1) {
- distinctCount++;
- }
- end++;
- while (distinctCount > 2) {
- char startChar = s.charAt(start);
- map.put(startChar, map.get(startChar) - 1);
- if (map.get(startChar) == 0) {
- distinctCount--;
- }
- start++;
- }
- maxLen = Math.max(maxLen, end - start);
- }
- return maxLen;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement