原题链接:3. 无重复字符的最长子串 – 力扣(LeetCode)
思路:暴力至少是O(n^2),对于子串问题,可以采用双指针,滑动窗口等方法
class Solution {
public int lengthOfLongestSubstring(String s) {
//map记录的是对应字符,最近出现的下标
HashMap<Character, Integer> map = new HashMap<>();
int n = s.length();
int left = 0;
int max = 0;
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
//将left更新为当前重复字符的下一个位置,保证区间内没重复元素
left = Math.max(map.get(ch) + 1, left);
}
//随时更新字符最近出现的下标
map.put(ch, i);
max = Math.max(max, i - left + 1);
}
return max;
}
}