LEETCODE

#3. Longest Substring Without Repeating Characters [MEDIUM]

로그앤 2023. 10. 7. 14:51

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

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

 

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

 

Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.


 
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        left = 0
        charSet = set()
        longest = 0
        for right in range(len(s)): # traverse right ptr
            while s[right] in charSet: # if curr in SET
                charSet.remove(s[left]) # remove the corresponding duplicate in left
                #print("REMOVING:", s[left])
                left += 1 # move left ptr
            charSet.add(s[right]) # add the curr char
            #print(charSet)
            longest = max(longest, right - left + 1) #longest = sliding window length
        return longest  

[a,b,c,a,b,c,b,b]

l = 0, r = 0 charSet = {a}
l = 0, r = 1 charSet = {a, b}
l = 0, r = 2 charSet = {a, b, c}
l = 1, r = 3 charSet = {b,c} --> {b,c,a} // remove 'a' --> increment left to 1 --> add 'a' to charSet

...

https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/?envType=featured-list&envId=top-interview-questions?envType=featured-list&envId=top-interview-questions