美文网首页Leetcode每日两题程序员
Leetcode 159. Longest Substring

Leetcode 159. Longest Substring

作者: ShutLove | 来源:发表于2017-10-31 18:39 被阅读13次

    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;
    }

    相关文章

      网友评论

        本文标题:Leetcode 159. Longest Substring

        本文链接:https://www.haomeiwen.com/subject/sotipxtx.html