leetcode之 Longest Substring Without Repeating Characters

problem:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

看題意,輸入是一串字符串,輸出是沒有重複元素的子字符串的長度。
分析:
這是一個最優解的問題,例如:abcabcbb ,如果已經找到abcabcb的最優長度max,那麼abcabcbb的長度是多少呢?

public int lengthOfLongestSubstring1(String s) {
        if(s==null || s.equals(""))
            return 0;  
        char[] sArray=s.toCharArray();
        ArrayList<Character> sum=new ArrayList<Character>();
        int max=1;
        sum.add(sArray[0]);
        for(int i=1;i<sArray.length;i++){
            if(sum.contains(sArray[i]) ){
                int index=sum.indexOf(sArray[i]);
                sum.removeAll(sum.subList(0,index+1));
                sum.add(sArray[i]);
            }else{
                sum.add(sArray[i]);
            }
            max=Math.max(max,sum.size());
        }
        return max;
    }

先把求出來的子串最大的長度放入max,然後遍歷下一個字符,看它是否存在在前面的字符串,如果存在,那麼一個不包含重複元素的新的字串,必定是要把重複元素以及它前面的元素清空,然後再把它的長度和max比較,就可以得出最新的長度。

但是,我這種解法,雖然思想上是對的,但是在實現上確實很粗糙,實現最精緻的是leetcode上速度最快的那種。

public int lengthOfLongestSubstring(String s) {

        int i=0;
        int j=0;
        int max=0;
        HashSet<Character> set=new HashSet<Character>();
        while (j<s.length()){
            if(!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                max=Math.max(max,set.size());
            }else{
                set.remove(s.charAt(i++));
            }
        }
        return max;
    }

思想上是一致的。實現上的差距:
1.爲了遍歷,我把字符串轉換成了字符數組。實際上,可以通過
s.charAt(i).就可以像數組一樣遍歷。
2.爲了清空重複元素以及所有前面的元素,我是通過ArrayList中的
sum.removeAll(sum.subList(0,index+1)); 移除字串的形式。
實際上,通過兩個指針可以解決這個問題。
指針 j 用來表示遍歷到哪一個元素。
指針 i 用來表示重複元素的位置。
利用set.remove(s.charAt(i++)) 一直運行到移除重複元素的位置,於是set中就只含有後面字串的元素。

發佈了33 篇原創文章 · 獲贊 16 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章