longest substring without repeating characters – leetcode a3

Problem

Problem description.

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

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

Analysis

  • Sliding window

Python Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class :
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
ss = set()
start = 0
maxlen = 0
for i, x in enumerate(s):
while x in ss:
ss.remove(s[start])
start += 1
ss.add(x)
maxlen = max(maxlen, i - start + 1)
return maxlen