[leetcode]3-Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

1)題目

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

2)思路

先寫一個子函數,輸入數組下標,母字符串,日後遍歷,得到下標出最長子串長度。
遍歷母字符串,調用子函數,得到每一位長度,放入數組裏。
獲取數組最大值。數組

3) 代碼

public int lengthOfLongestSubstring(String s) {
        if("".equals(s)||s==null){
            return 0;
        }
        int[] len = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            len[i]=getLongSubString(i,s);
        }
        int asInt = Arrays.stream(len).max().getAsInt();
        return asInt;

    }
    private int getLongSubString(int i, String s) {
        String sb = String.valueOf(s.charAt(i));

        for (int j = i+1; j < s.length(); j++) {
            if (sb.contains(String.valueOf(s.charAt(j)))) {
                return j - i ;
            }else {
                sb += s.charAt(j);
            }
        }
        return s.length()-i ;


    }

4) 結果

時間複雜度:O(n^2)
空間複雜度:O(n)
耗時:326 ms函數

5) 調優

v2

其實只用一次遍歷就夠了。
設置一個「滑窗」,
left 記錄最新左邊不重複下標。
這時候就要添加一個字符map,至關於一個hashmap。 只不過直接用字符編碼作key,字符下標作value。
new int[256] 初始爲-1
再申請一個res,記錄最大滑窗值編碼

好比acabaa
當遇到第二a時, left = m[a] == 0
res = 2
這時候能夠繼續日後走,到b res=3
到第三個a時候, left = m[a] ==2
滑窗就從這個a開始了。code

這算是一個針對該題的 」巧妙「 解法 暫時不知道有沒有通用性字符串

public int lengthOfLongestSubstring(String s) {
        int[] m = new int[256];
        Arrays.fill(m, -1);
        int res = 0, left = -1;
        for (int i = 0; i < s.length(); ++i) {
            left = Math.max(left, m[s.charAt(i)]);
            m[s.charAt(i)] = i;
            res = Math.max(res, i - left);
        }
        return res;
    }
相關文章
相關標籤/搜索