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. Note that "bca" and "cab" are also correct answers.
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 * 104sconsists of English letters, digits, symbols and spaces.
My Answer
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
substring = dict() # char, last_appearance_index
length = 0
max_length = 0
best_solution_set = None
index = 0
while index < len(s):
if s[index] not in substring:
substring[s[index]] = index
length += 1
else:
if length > max_length:
best_solution_set = substring
max_length = length
index = substring[s[index]]+1 # change to index last repeated character
if index >= len(s):
break
substring = {s[index]:index}
length = 1
if length > max_length:
best_solution_set = substring
max_length = length
index = index + 1
print(best_solution_set)
return max_lengthLeetCode - The World’s Leading Programming Learning Platform
technical interview