2022-4-24 滑动窗口
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
1 class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 int l=0,r=0,ans=0; 4 Set<Character> set=new HashSet<>(); 5 while (r<s.length()){ 6 char c=s.charAt(r); 7 if (!set.contains(c)){ 8 set.add(c); 9 r++; 10 ans=Math.max(ans,r-l); 11 }else{ 12 while (l<r&&set.contains(c)){ 13 set.remove(s.charAt(l)); 14 l++; 15 } 16 } 17 } 18 return ans; 19 } 20 }
思路:直接用set判断当前子串的字符,滑动窗口。
浙公网安备 33010602011771号