Java HashSet solution


  • 0
    G

    I saw most methods here are HashMap; so I tried HashSet, which looks simpler.

    class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            if (s == null || s.length() == 0) return 0;
            int start = 0, end = 0, max = 0;
            Set<Character> set = new HashSet<>();
            while (end < s.length()) {
                set.add(s.charAt(end));
                if (set.size() > 2) {
                    int tmp = end;
                    Set<Character> tmpset = new HashSet<>();
                    while (tmpset.size() <= 2) tmpset.add(s.charAt(tmp--));
                    start = tmp + 2;
                }
                max = Math.max(max, end - start + 1);
                    
                end++;
            }
            return max;
        }
    }
    

Log in to reply
 

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