Simple Java Solution beats 90% 7 lines


  • 0
    D

    Since there are many ways using hashtable,
    In this solution I replace hashtable by array, both the lines and time consume decrease a lot!
    the thoughts is same as those hashtable way--- is still two pointers.

    public class Solution {

        public int lengthOfLongestSubstringTwoDistinct(String s) {
            int max=0;char[] map=new char[128];int count=2;
            for(int i=0,j=0;i<s.length();i++){
                if(map[s.charAt(i)]++==0){count--;}
                while(count<0){
                    if(--map[s.charAt(j++)]==0){count++;}
                }
                max=Math.max(max,i+1-j);
            }
            return max;
        }
    

    }


Log in to reply
 

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