2015年10月24日星期六

Leetcode 159 Longest Substring with At Most Two Distinct Characters

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.
Solution 1: Use slid window. Maintain count number<2 and keep updating the result.
 public class Solution {  
   public int lengthOfLongestSubstringTwoDistinct(String s) {  
     int n=s.length();  
     int[] c=new int[256];  
     int i=0, count=0, res=0;  
     for (int j=0; j<n; j++) {  
       if (c[s.charAt(j)]++==0) count++;  
       if (count>2) {  
         while (--c[s.charAt(i++)]>0) continue;  
         count--;  
       }  
       res=Math.max(res,j-i+1);  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论