nathanwailes

LeetCode 3 - Longest Substring Without Repeating Characters - 2022.12

Dec 30th, 2022
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLongestSubstring(self, s: str) -> int:
  3.         """ How to solve it: we're going to move a sliding window through the input,
  4.        maintaining a dictionary of the characters in the current window, as well as a
  5.        variable tracking how many of the entries in the dict have more than one
  6.        character.  We'll update a variable tracking the length of the longest substring
  7.        whenever the dict doesn't have any characters with more than one entry in the
  8.        current window.  We'll advance the right pointer as long as the current window
  9.        doesn't have any duplicates, and we'll advance the left pointer as long as the
  10.        current window *does* have duplicates.
  11.        """
  12.         longest_substring = 0
  13.         l = 0
  14.         r = 0
  15.         current_window_dict = defaultdict(int)
  16.         chars_in_dict_with_dupes = 0
  17.  
  18.         def we_could_still_find_a_substring():
  19.             return l <= r and r < len(s)
  20.  
  21.         while we_could_still_find_a_substring():
  22.             while chars_in_dict_with_dupes == 0 and r < len(s):
  23.                 longest_substring = max(longest_substring, r - l)
  24.                 current_window_dict[s[r]] += 1
  25.                 if current_window_dict[s[r]] == 2:
  26.                     chars_in_dict_with_dupes += 1
  27.                 r += 1
  28.            
  29.             while chars_in_dict_with_dupes > 0 and l <= r:
  30.                 current_window_dict[s[l]] -= 1
  31.                 if current_window_dict[s[l]] == 1:
  32.                     chars_in_dict_with_dupes -= 1
  33.                 l += 1
  34.            
  35.         if chars_in_dict_with_dupes == 0:
  36.             longest_substring = max(longest_substring, r - l)
  37.            
  38.  
  39.         return longest_substring
Advertisement
Add Comment
Please, Sign In to add comment