My Java soln - 99.64%


  • 0
    R
    public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        char oneBefore='.', twoBefore='-';
        int currentCount = 0, max = 0;
    
        char[] cs = s.toCharArray();
        for(int i=0; i< cs.length; i++){
            if(cs[i] == oneBefore || cs[i] == twoBefore) {
                currentCount++;
            }
            else{
                currentCount = updateCount(cs,i);
                oneBefore = cs[i];
                if(i>=1){
                    twoBefore = cs[i-1];
                }
            }
            if (currentCount > max){
                max=currentCount;
            }
        }
        return max;
    }
    public int updateCount(char[] s, int i){
        int count = 1;
        if (i<=0){
            return count;
        }
        int j = i-1;
        while(j>=0){
            if(s[i-1] == s[j]){
                count++;
            }
            else{
                break;
            }
            --j;
        }
        return count;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.