无重复字符的最长字串长度
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
题解:
双指针+哈希表(记录双指针之间的字符)
1 class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 int ans = 0; 4 HashSet<Character> hs = new HashSet<>(); 5 int l = 0, r = 0; 6 while(r < s.length()) { 7 if(!hs.contains(s.charAt(r))) { 8 hs.add(s.charAt(r)); 9 ans = Math.max(ans, r - l + 1); 10 r ++; 11 } 12 else { 13 while(l < r && hs.contains(s.charAt(r))) { 14 hs.remove(s.charAt(l)); 15 l ++; 16 } 17 } 18 } 19 return ans; 20 } 21 }
浙公网安备 33010602011771号