public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); //max的作用是保证i不会突然变小, 例如abbba, 到最后一个a的时候如果没有max,这个i会突然变小导致算错 } ans = Math.max(ans, j - i + 1); j表示当前索引 , i是最左边的位置, 当前范围是从i到j 全包含, 所以+1 map.put(s.charAt(j), j + 1); 更新字符索引,这里的+1意思是存该字符靠右一个位置;因为必须考虑初始情况, } return ans; } }