LeetCode Hot100_3.无重复字符的最长字串
题目链接:
https://leetcode.cn/problems/longest-substring-without-repeating-characters/?envType=study-plan-v2&envId=top-100-liked
滑动窗口:
如果扫描到重复了的字符,就重新计算左侧pre指针的位置,pre 是无重复子串的起始位置,更新为 map.get(s.charAt(i)) + 1,即上一次出现该字符的位置的下一个位置。
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()<1)return 0;
Map<Character, Integer> map = new HashMap<>();
int max = 0;
int count = 1;
int pre = 0;
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
pre = Math.max(pre, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i-pre+1);
}
return max;
}
}

浙公网安备 33010602011771号