剑指 Offer 48. 最长不含重复字符的子字符串
滑动窗口代码
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() < 1) {
return 0;
}
int maxNumber = 1;
// 双端队列
Deque<Character> queue = new LinkedList<>();
queue.add(s.charAt(0));
// 记录位置
HashMap<Character, Integer> map = new HashMap<>();
map.put(s.charAt(0), 0);
for (int i = 1; i < s.length(); i++) {
// 如果队列要当前加入的元素在队列中已有
if (map.get(s.charAt(i)) != null) {
// 抛出重复元素之前的所有元素
while (!queue.isEmpty() && queue.getFirst() != s.charAt(i)) {
// 清空重复元素之前的所有映射
map.remove(queue.getFirst());
queue.removeFirst();
}
queue.removeFirst();
}
// 更新元素的位置
map.put(s.charAt(i), i);
queue.add(s.charAt(i));
maxNumber = Math.max(maxNumber, queue.size());
}
return maxNumber;
}