【leetcode3】 3. Longest Substring Without Repeating Characters解題報告

  • 關(guān)鍵字:最長不重復(fù)子串、雙指針
  • 難度:Medium
  • 題目大意:求一個字符串最長不重復(fù)子串的長度
題目:

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.

思路:

使用兩個指針l、r分別記錄不重復(fù)子串的起始和終止位置,l、r初始值為0,使用set來放當(dāng)前不重復(fù)的字符,r向右移動:

  • 字符不重復(fù)時,直接將字符add到set,r繼續(xù)向右移動;
  • 字符重復(fù)時,l向右移動,同時set刪除掉字符串l位置的字符;
  • 重復(fù)上述步驟;
思路實現(xiàn):
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0||s==null) return 0;
        int maxLen = 1;
        int l = 0;
        int r = 1;
        Set<Character> set = new HashSet<>();
        set.add(s.charAt(l));
        while(l<s.length()&&r<s.length()) {
            if(!set.contains(s.charAt(r))) {
                set.add(s.charAt(r));
                maxLen = Math.max(maxLen, r-l+1);
                r++;
            }
            else {
                set.remove(s.charAt(l));
                l++;
            }
        }
        return maxLen;
        
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容