3. Longest Substring Without Repeating Characters(HashSet + 雙指針)

Longest Substring Without Repeating Characters

【題目】

Given a string, find the length of the longest substring without repeating characters.

(給定一個字符串,找字符中的最大非重複子串)

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

【分析】

首先,這道題目要求是“非重複最長子串”,所以我們應該在第一時間點想到用HashSet容器。

其次,我們用兩個指針,一個遍歷數組,另一個檢測是否有重複的字符。如果發現重複字符,則remove。

最後用Math.max()函數記錄最大的長度即可。

Java實現代碼如下:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int res = 0;
        if (s == null || s.length() == 0) return res; 
        //注意區別字符串的length()方法與數組的length屬性
        HashSet<Character> set = new HashSet<>();
        for (int i = 0, j = 0; i < s.length();) {
            if (set.contains(s.charAt(i))) {
                set.remove(s.charAt(j++));
            } else {
                set.add(s.charAt(i++));
                res = Math.max(res, set.size());
            }
        }
        return res;
    }
}

 

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