Slide window solution with Java


  • 0
    R

    public int lengthOfLongestSubstringTwoDistinct(String s) {
    if(s == null || s.length() == 0) return 0;
    // http://www.studytrails.com/java/java8/java8_collections_new_methods/ (java 8 new method)
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    int res = Integer.MIN_VALUE;
    int left = 0;
    int right = 0;
    while (right < s.length()) {
    // add right position element to hashmap
    char ch = s.charAt(right);
    if(map.containsKey(ch)) {
    map.put(ch, map.get(ch)+1);
    } else {
    map.put(ch, 1);
    }
    // judge whether map.size >= 2;
    if(map.size() <= 2) {
    res = Math.max(res, right-left+1);
    } else {
    while(left < right && map.size() > 2) {
    char chl = s.charAt(left);
    if(map.get(chl) == 1) {
    map.remove(chl);
    } else {
    map.put(chl, map.get(chl)-1);
    }//? map.remove(chl) : map.put(chl, map.get(chl)-1);
    left++;
    }
    }
    right++;
    }
    return res;
    }


Log in to reply
 

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