类似于双指针的思想,将字符存入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;
    }