본문 바로가기
알고리즘/LeetCode

[Python] Longest Substring Without Repeating Characters - LeetCode

by Jun Shim 2021. 9. 16.
728x90

3. Longest Substring Without Repeating Characters

 

Longest Substring Without Repeating Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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


 

Examples

1:

Input: s = "abcabcbb"
Output: 3

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

 

2:

Input: s = "bbbbb"
Output: 1

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

 

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.

 

4:

Input: s = ""
Output: 0

 

Constraints:

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

 

Python solution

Python
Accepted 52ms runtime

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        used = dict()
        max_length = start = 0

        for i, c in enumerate(s):
            if c in used and start <= used.get(c):
                start = used.get(c) + 1
            else:
                max_length = max(max_length, i - start + 1)

            used[c] = i

        return max_length

 

728x90

댓글