美文网首页
LeetCode每日一题:longest substring w

LeetCode每日一题:longest substring w

作者: yoshino | 来源:发表于2017-07-06 10:41 被阅读33次

    问题描述

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    问题分析

    一般查找是否重复最简便的方法就是hashMap,这道题只要求我们返回长度大小,我们可以采用滑动窗口的方式来进行。

    代码实现

    public int lengthOfLongestSubstring(String s) {
            if (s.length() == 0) return 0;
            HashMap<Character, Integer> hashMap = new HashMap<>();
            int leftBound = 0;
            int max = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                int isSame = 0;
                if (hashMap.containsKey(c)) isSame = hashMap.get(c) + 1;
                leftBound = Math.max(leftBound, isSame);
                max = Math.max(max, i - leftBound + 1);
                hashMap.put(c, i);
            }
            return max;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:longest substring w

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