题目:https://leetcode.cn/problems/longest-substring-without-repeating-characters/
解法:
1.滑动窗口 时间:o(n) 空间:o(1)
思路:
a.两个指针,记录窗口的头尾位置
b.判断新数据在当前窗口中是否重复,重复直接将窗口头部位置移动到重复位置的下一个
c.当前数据进入窗口,更新最大窗口长度
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0;
int max = 0;
Map<Character,Integer> kvs = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(kvs.containsKey(c))
left = Math.max(kvs.get(c) + 1, left); //和left比较是要确保重复数据在窗口中,如果不在窗口中,不需要移动left指针
kvs.put(c,i);
max = Math.max(i - left + 1,max); // 窗口大小是 i - left + 1
}
return max;
}
}