原题链接在这里:
题目:
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”
,
T is "ece" which its length is 3.
题解:
与类似。快慢指针维护substring的方法在里有总结.
runner 扫过 char的frequency加一. 条件count++.
当count > 2后移动walker直到count减到2
Time Complexity: O(n), 窗口只移动一遍. Space: O(1). map size.
AC Java:
1 public class Solution { 2 public int lengthOfLongestSubstringTwoDistinct(String s) { 3 int res = 0; 4 int [] map = new int[256]; 5 int walker = 0; 6 int runner = 0; 7 int count = 0; 8 while(runner < s.length()){ 9 if(map[s.charAt(runner++)]++ == 0){10 count++;11 }12 while(count > 2){13 if(map[s.charAt(walker++)]-- == 1){14 count--;15 }16 }17 res = Math.max(res, runner - walker);18 }19 return res;20 }21 }
类似.