Java Concise solution


  • 0
    V
    public class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            // c1, c2 are pointers that keep track of the characters.
            // if the some other character comes in, we move back as much as we can.
            // update the character to be used and start and then continue.
            Set<Character> lookup = new HashSet<>();
            int lo = 0, maxLen = 0;
            char[] A = s.toCharArray();
            for (int hi = 0; hi < A.length; hi++) {
                if(!lookup.contains(A[hi])) {
                    if (lookup.size() <2) lookup.add(A[hi]);
                    else {
                        lookup = new HashSet<>();
                        lo = hi - 1;
                        lookup.add(A[lo]);
                        while(lo > 0 && A[lo] == A[lo - 1]) lo--;
                        lookup.add(A[hi]);
                    }
                }
                maxLen = Math.max(maxLen, hi - lo + 1);
            }
            
            return maxLen;
        }
    }
    

Log in to reply
 

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