Longest substring without repeating characters#

Levels: level-4
Data structures: string, hash-table
Patterns: sliding-window

LeetCode

Description#

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

Examples#

1Input: "abcabcbb"
2Output: 3
3Explanation: The answer is "abc", with the length of 3.
1Input: "pwwkew"
2Output: 3
3Explanation: The answer is "wke", with the length of 3.
4Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Python Solution#

 1class Solution:
 2    # @return an integer
 3    def lengthOfLongestSubstring(self, s):
 4        used = {}
 5        max_length = start = 0
 6        for i, c in enumerate(s):
 7            if c in used and start <= used[c]:
 8                start = used[c] + 1
 9            else:
10                max_length = max(max_length, i - start + 1)
11
12            used[c] = i
13        return max_length