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.

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.

Solution:
基本想法:維護一個hashmap,其中字符為key,位置為value,同時維護兩個指針用于計算最長子串。右指針掃描,同時更新hashmap。如果某個字符已經在hashmap里面,將左指針移動到上一次發現該字符的右一位。注意兩個指針可以同時移動。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0)    return 0;
        Map<Character, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0, j = 0; i < s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j, map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i-j+1);
        }
        return max;
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 很久以前,我便想寫一寫我的母親,但總覺得手中的筆很重,無從下手。促使我今天動筆的,卻是近幾個月來,母親的聽力日漸減...
    聆聽萬籟閱讀 338評論 6 10
  • 從2016年開始零基礎摸索畫水彩,一直到現在,記錄下自己的小快樂。
    倉央梅朵閱讀 472評論 1 1
  • 曾經 在枝頭光鮮 母親把孩子舉過頭頂 一陣秋風吹來 母親放手,孩子獨行 從天上降臨凡間 塵埃,塵埃,塵埃 光鮮一夜...
    張一冉閱讀 181評論 0 0
  • 暢所欲言那是曾經 當把奢望說出口 又有幾分悔意 本不想讓彼此回到那個沉默的當初 不知是哪來的勇氣 想要一句來自寒冬...
    蕭谷南溪微辭閱讀 129評論 2 8