LeetCode: Longest Substring Without Repeating Characters

Find the length of the longest substring without repeating characters.

Posted on LeetCode Python

See original problem on leetcode.com

Difficulty: Medium

Given a string s, find the length of the longest substring that contains no repeating characters.

Solution

Initialize the list of unique characters - chars - to an empty list. Iterate over every character char in s.

If char is already in chars, remove all characters up to and including the first occurrence of char from chars.

Example:

Append char to the end of chars.

Return the longest chars seen.

Runtime

15 ms | Beats 80.95%

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
best = 0
chars = []
for char in s:
if char in chars:
chars = chars[chars.index(char) + 1:]
chars.append(char)
if len(chars) > best:
best = len(chars)
return best