nathanwailes

LeetCode 3 - Longest Substring Without Repeating Characters - 2023.10.13 solution

Oct 13th, 2023
846
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLongestSubstring(self, s: str) -> int:
  3.         """ Thought: We can have two pointers, with a set listing
  4.        all the characters contained in the span between them. We
  5.        advance the right pointer until we hit a duplicate, at
  6.        which point we advance the left pointer. We use a separate
  7.        variable to keep track of the largest substring we've
  8.        encountered.
  9.        """
  10.         l = 0
  11.         r = 0
  12.  
  13.         if len(s) == 0:
  14.             return 0
  15.  
  16.         span_set = set([s[0]])
  17.         largest_substring = 1
  18.  
  19.         while r < len(s) - 1:
  20.             r += 1
  21.             while s[r] in span_set:
  22.                 span_set.remove(s[l])
  23.                 l += 1
  24.             span_set.add(s[r])
  25.             largest_substring = max(largest_substring, r - l + 1)
  26.        
  27.         return largest_substring
  28.  
Advertisement
Add Comment
Please, Sign In to add comment