题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

http://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7

类似于双指针的思想,将字符存入map中,若map中存在相同字符,则取最右边的字符下标+1,需要注意的是left指针取的是所有字符最右边的下标,以防其他字符在[left + 1, i]区间内出现重复的情况。

  public int lengthOfLongestSubstring (String s) {
        // write code here
        HashMap<Character, Integer> hashMap = new HashMap<>();
        char[] chars = s.toCharArray();
        int left = 0, maxLength = 0;
        for (int i = 0; i < chars.length; i++){
            if (hashMap.containsKey(chars[i])){
                left = Math.max(left, hashMap.get(chars[i]) + 1);
            }
            hashMap.put(chars[i], i);
            maxLength = Math.max(maxLength, i - left + 1);
        }
        return maxLength;
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务