1. 程式人生 > >3無重複最長子串

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;
    }
}