nathanwailes

LeetCode 3 - Longest Substring Without Repeating Characters - 2023.01.05 solution

Jan 4th, 2023
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLongestSubstring(self, s: str) -> int:
  3.         """ How to solve it: Sliding window: Maintain a set of characters in the current window.  Advance the
  4.        right pointer as long as you don't have any duplicates.  As soon as you have a duplicate, advance the left
  5.        pointer until the duplicate is removed.
  6.        """
  7.         current_window_chars = set()
  8.         res = 0
  9.         l = 0
  10.         for r in range(len(s)):
  11.             while s[r] in current_window_chars:
  12.                 current_window_chars.remove(s[l])
  13.                 l += 1
  14.             current_window_chars.add(s[r])
  15.             res = max(res, r - l + 1)
  16.         return res
Advertisement
Add Comment
Please, Sign In to add comment