Longest Substring with At Most Two Distinct

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.spa

For example, Given s = 「eceba」,code

T is "ece" which its length is 3.blog

用p1 & p2 兩個pointer分別紀錄當前window裏兩個character最後一次發生時的index,用start紀錄window開始時的index。
從index 0開始遍歷String:string

若是當前的character在window內,update相應的pointer。it

若是不在,比較兩個character的pointer,去掉出現較早的那個character, 更新start=min(p1,p2)+1io

時間複雜度是O(n), 空間複雜度是O(1):class

 

 1 public class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         int result = 0;
 4         int first = -1, second = -1;
 5         int win_start = 0;
 6         for(int i = 0; i < s.length(); i ++){
 7             if(first < 0 || s.charAt(first) == s.charAt(i)) first = i;
 8             else if(second < 0 || s.charAt(second) == s.charAt(i)) second = i;
 9             else{
10                 int min = first < second ?  first : second;
11                 win_start = min + 1;
12                 if(first == min) first = i;
13                 else second = i;
14             }
15             result = Math.max(result, i - win_start + 1);
16         }
17         return result;
18     }
19 }
相關文章
相關標籤/搜索