题目描述
题目链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters/
思路
首先想到了双指针控制窗口,无重复的字符又想到Map存储。
- 遍历一遍字符串
- 初始start指向0,end指向当前遍历字符的下标
- Map存储每个字符,map结构为<character,interger>,整数为当前的索引下标+1
- 如果遇到重复的字符
map.containsKey(c)
, 更新start为map当前字符的value - 每一次都计算子串长度ans = max(ans, end- start + 1),更新map当前字符对应的value值
实现
class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length();int ans = 0;Map<Character,Integer> map = new HashMap<>();for(int end = 0, start = 0; end < n; end++){char c = s.charAt(end);if(map.containsKey(c)){start = Math.max(map.get(c),start);}ans = Math.max(ans, end - start + 1);map.put(s.charAt(end), end + 1);}return ans;}
}