leetCode刷題記錄-3. Longest Substring Without Repeating Characters

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.code

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.get

 

這裏我想到了兩種解法,一種是利用map,一種是利用數組,思想差很少,可是數組寫的貌似有點醜陋,string

這道題的主要解法就是判斷最長的不重複字符的子串,考慮到若是字符重複的時候,把這個字符上一次出現的地方的後一位做爲起點就可以保證字符串沒有重複,因此確定要找到這個重複字符的上一個出現的地方的後一位做爲長度計算的地方,因此我想到利用map來以字符做爲key,以字符上一次所在的位置做爲value,當map不包含key的時候,說明字符尚未重複,當包含的時候就已經重複了,這時候比較len的長度,若是這時候的不重複的字符串的長度大於len那麼就把len修改成不重複字符串的長度,而後繼續下一次的比較,總的算法複雜度爲O(n)。(其實好像畫圖更容易讓人理解,可是我比較懶O__O "…)數組的實現思想也差很少相似it

public class Solution3 {
    /**
     * 解法一
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> charMap = new HashMap<>();
        int strSize = s.length();
        int first = 0;
        int len = 0;
        int index;
        char key;
        for (int last = 0; last < strSize; last++) {
            key = s.charAt(last);
            if (charMap.containsKey(key)) {
                index = charMap.get(key)+1;////將first移動到上一次出現這個字符的後一位
                if (index > first) {//first必須在上一個字符出現的地方以前,由於可能多個重複的字符會移動到當前的first以前,例如abcddabc
                    first = index;
                }
            }
            if (last - first + 1 > len) {
                len = last - first+1;
            }
            charMap.put(key,last);
        }
        return len;
    }

    /**
     * 解法二
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring1(String s) {
        int[] charArr = new int[256];
        int strSize = s.length();
        int first = 0;
        int len = 0;
        int index;
        char key;
        for (int last = 0; last < strSize; last++) {
            key = s.charAt(last);
            if (charArr[key] != 0) {
                if (charArr[key] == -1) {
                    charArr[key] = 0;
                    index = 1;
                } else {
                    index = charArr[key]+1;
                }
                if (index > first) {
                    first = index;
                }
            }
            if (last - first + 1 > len) {
                len = last - first+1;
            }
            if (last == 0) {
                charArr[key] = -1;
            } else {
                charArr[key] = last;
            }
        }
        return len;
    }
}
相關文章
相關標籤/搜索