Leetcode 159. Longest Substring with At Most Two Distinct Characters

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”,

T is “ece” which its length is 3.

思路:
遍历字符串,用哈希表存储遍历到的字符当前最右的位置。
如果哈希表大小大于2,证明当前有3个不同的字符,需要去掉一个,把位置最靠左的去掉,就能够算出到当前字符为止,最长的len是多大。

public int lengthOfLongestSubstringTwoDistinct(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    Map<Character, Integer> map = new HashMap<>();
    int res = 0;
    int left = -1;
    for (int i = 0; i < s.length(); i++) {
        map.put(s.charAt(i), i);
        if (map.size() > 2) {
            int leftest = s.length();
            for (Character c : map.keySet()) {
                leftest = Math.min(leftest, map.get(c));
            }
            left = leftest;
            map.remove(s.charAt(leftest));
        }
        res = Math.max(res, i - left);
    }

    return res;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/d914c0d37958
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞