1.题目介绍
2.解法
关键是确定左指针的位置,应取当前left和该字符上次出现的位置中的较大值,而不是取该字符上次出现的位置。
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> hash = new HashMap<>();
// 初始化左指针 left 为 -1,无重复子串的长度res 为 0,字符串长度 len 为 s 的长度
int left = -1, res = 0, len = s.length();
// 遍历字符串 s,使用 i 作为右指针
for(int i = 0; i < len; i++) {
if (hash.containsKey(s.charAt(i))){
// 更新左指针left,取当前left和该字符上次出现的位置中的较大值
left = Math.max(left, hash.get(s.charAt(i)));
}
// 更新结果 res,取当前结果和右指针 i 与左指针 left 的差值中的较大值
hash.put(s.charAt(i), i);
res = Math.max(res, i - left);
}
// 返回最长无重复子串的长度
return res;
}
}