Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def lengthOfLongestSubstring(self, s: str) -> int:
- """ How to solve it: we're going to move a sliding window through the input,
- maintaining a dictionary of the characters in the current window, as well as a
- variable tracking how many of the entries in the dict have more than one
- character. We'll update a variable tracking the length of the longest substring
- whenever the dict doesn't have any characters with more than one entry in the
- current window. We'll advance the right pointer as long as the current window
- doesn't have any duplicates, and we'll advance the left pointer as long as the
- current window *does* have duplicates.
- """
- longest_substring = 0
- l = 0
- r = 0
- current_window_dict = defaultdict(int)
- chars_in_dict_with_dupes = 0
- def we_could_still_find_a_substring():
- return l <= r and r < len(s)
- while we_could_still_find_a_substring():
- while chars_in_dict_with_dupes == 0 and r < len(s):
- longest_substring = max(longest_substring, r - l)
- current_window_dict[s[r]] += 1
- if current_window_dict[s[r]] == 2:
- chars_in_dict_with_dupes += 1
- r += 1
- while chars_in_dict_with_dupes > 0 and l <= r:
- current_window_dict[s[l]] -= 1
- if current_window_dict[s[l]] == 1:
- chars_in_dict_with_dupes -= 1
- l += 1
- if chars_in_dict_with_dupes == 0:
- longest_substring = max(longest_substring, r - l)
- return longest_substring
Advertisement
Add Comment
Please, Sign In to add comment