【LeetCode】3無重複字符的最長子串

思路:使用雙向隊列。遍歷字符串,如果隊列不包含當前字符,則將該字符添加到隊列末尾;如果隊列已經包含了當前字符,首先記錄當前隊列長度,然後將隊列該字符之前的所有字符全部彈出,然後將當前字符添加到隊列末尾,維持隊列不出現重複的字符。

    public int lengthOfLongestSubstring(String s) {
        if(s==null||s.length()==0) return 0;

        int answer=0;
        int length=s.length();
        LinkedList<Character> window=new LinkedList<>();

        for(int i=0;i<length;i++){
            if(window.contains(s.charAt(i))){
                //若包含當前字符,記錄當前答案,將該字符之前的所有元素全部彈出
                answer=answer<window.size()?window.size():answer;
                while(!window.isEmpty()&&window.poll()!=s.charAt(i));
            }
            //當前字符添加到隊列的末尾
            window.add(s.charAt(i));
        }

        //當整個字符串都沒有重複的元素,這一句就發揮作用了
        return Math.max(answer,window.size());
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章