알고리즘 스터디

[Leetcode/파이썬] 3. Longest Substring Without Repeating Characters

난쟁이 개발자 2025. 6. 4. 22:31
반응형

Longest Substring Without Repeating Characters

Difficulty: Medium


Given a string s, find the length of the longest substring without duplicate 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.

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

 

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        cnt = 0
        left = 0
        char_set = set()

        for right in range(len(s)) :
            while s[right] in char_set :
                char_set.remove(s[left])
                left += 1
            
            char_set.add(s[right])
            cnt = max(cnt, right - left + 1)
        
        return cnt

 

반응형