LeetCode 3 無重複字符的最長子串 我的題解記錄

在這裏插入圖片描述
這道題使用雙指針(滑動窗口)+哈希表可破。


public int lengthOfLongestSubstring(String s) {
        if (s==null||s.equals(""))
            return 0;
        int start = 0;
        int end = 0;
        char[] arr = s.toCharArray();
        int[] hash = new int[128];  //構建一個字母哈希表
        hash[arr[0]-1] = 1;
        int max = 1;
        for (int i = 1; i < s.length() ; i++) {
            if (hash[arr[i]-1]==0){     //如果start~end中還沒出現當前arr[i] 那麼就把它添加到哈希表中
                hash[arr[i]-1] = 1;     //置爲1 表示出現過
                end = i;                //更新end結點
                if (end-start+1>max)    //如果start~end長度大於max 更新max
                    max++;
            }else {                         //如果當前arr[i]在前面已經出現過 那我們要更新start結點
                while (arr[start]!=arr[i]){     //找到之前出現過arr[i]的位置i
                    hash[arr[start]-1] = 0;
                    start++;
                }
                start++;                    //把start置爲i的下一個
            }
        }
        return max;
}

官方題解的解法

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;
        }
        return ans;
    }
}

作者:LeetCode
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

好吧就是比我簡潔多了 。不過我覺得我按着我這個邏輯走 ,更清晰 ,更能一步就懂。二者效率差不多。

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