Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba" Output: 3 Explanation: tis "ece" which its length is 3.
Example 2:
Input: "ccaabbb" Output: 5 Explanation: tis "aabbb" which its length is 5.
public int lengthOfLongestSubstringTwoDistinct(String s) { if (s == null || s.length() == 0) { return 0; } char[] sArr = s.toCharArray(); int[] hash = new int[256]; int l = 0, count = 0, result = 1; for (int r = 0; r < sArr.length; ++r) { hash[sArr[r]]++; if (hash[sArr[r]] == 1) { count++; } while (count > 2) { hash[sArr[l]]--; if (hash[sArr[l]] == 0) { count--; } l++; } result = Math.max(result, r - l + 1); } return result; }