3无重复最长子串

官方答案,加了注释

public class Solution{
    public int lengthOfLongestSubstring(String s){
        int n=s.length(); //取得字符串s的长度
        Set<Character> set = new HashSet<>(); //新建set用来存储子字符串
        int ans=0,i=0,j=0; //ans为最长不重复子串的长度,i、j为窗口起终址
        while(i<n&&j<n){
            //如果set中未包含了s中第j个位置的字符,则将该字符加入set,并将j加1(扩大窗口)
            //将ans置为ans和j-i两者中较大的值
            if(!set.contains(s.charAt(j))){ 
                set.add(s.charAt(j++));
                ans=Math.max(ans,j-i);
            }else{
                //如果set中已包含了s中第j个位置的字符,则将s中i位置字符从set中删除,并将i加1(后移窗口)
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}


 

猜你喜欢

转载自blog.csdn.net/zcy_wxy/article/details/85371831