【算法】雙索引技術(滑動窗口)--無重複字符的最長子串

3. 無重複字符的最長子串

public class LengthOfLongestSubstring3 {
    public static void main(String[] args) {
        String s = "abcabcbb";
        System.out.println(lengthOfLongestSubstring(s));
    }

    private static int lengthOfLongestSubstring(String s) {
        // 定義左右兩個指針
        int left = 0, right = -1;
        // 字符標記
        int[] freq = new int[256];
        // 長度
        int length = 0;
        while (left < s.length()) {
            if (right + 1 < s.length() && freq[s.charAt(right + 1)] == 0) {
                freq[s.charAt(++right)]++;
            } else {
                freq[s.charAt(left++)]--;
            }
            length = Math.max(length, right - left + 1);
        }
        return length;
    }
}

其他文章:【算法】雙索引技術(滑動窗口)–長度最小的子數組

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