无重复字符的最长子串-滑动窗口

class Solution {
    public int lengthOfLongestSubstring(String s) {
        //滑动窗口
        Set<Character> set1=new HashSet<>();
        int ans=0;int i=0;int j=0;
        int n=s.length();
            while(i<n&&j<n){
                if(!set1.contains(s.charAt(j))){
                    set1.add(s.charAt(j++));
                    ans=Math.max(ans,j-i);
                } else{
                    set1.remove(s.charAt(i++));
                }           
            }
        return ans;
        
    }
}

猜你喜欢

转载自www.cnblogs.com/NeverGiveUp0/p/11142941.html