[LeetCode] No.3 Longest Substring Without Repeating Characters

鏈接:

https://leetcode.com/problems/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.

分析:

這道題方式還是要使用雙指針的方式,兩個游標,同時維護一個集合,一個游標標注左側index 一個游標標注右側index,在兩游標之間不能出現重復字符,當無重復的時候移動右側游標,一旦移動到重復移動左側游標,在此過程中記錄最大長度。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
            int j = 0;
        int length = 0;
        if(s.equals("")) {
            return 0;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            while (j < s.length() && (map.get(s.charAt(j))==null || map.get(s.charAt(j)) == 0)) {
                map.put(s.charAt(j), 1);
                length = Math.max(j-i, length);
                j++;

            }
            map.put(s.charAt(i),0);
        }
        return length+1;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容