一、题目内容
二、题解
解法1:
思路


- 通过hash表记录每个字符最晚一次出现的索引位置,用来求i
遍历到 s[j]时,可通过访问哈希表 dic[s[j]] 获取最近的相同字符的索引 i。
代码
class Solution {public int lengthOfLongestSubstring(String s) {Map<Character, Integer> dic = new HashMap<>();int res = 0, temp = 0, len = s.length();for (int j = 0; j < len; j++) {// 获取索引 iint i = dic.getOrDefault(s.charAt(j), -1);// 更新哈希表dic.put(s.charAt(j), j);//执行转移方程temp = temp < j - i ? temp + 1 : j - i;res = Math.max(res, temp);}return res;}}
