smj007

Longest Substring Without Repeating Characters

Apr 23rd, 2025
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLongestSubstring(self, s: str) -> int:
  3.  
  4.         """
  5.        At each step, right pointer points to a locations where we
  6.        are trying to calculate length of longest string ending there.
  7.        When we are iterating over the character corresponding to right pointer,
  8.        we might have added one of the duplicate characters already in the hashset
  9.        so we havwe to remove characters from left untill duplicate of s[right] is removed
  10.  
  11.        Think of it this way:
  12.        how will you calcuate the longest substring ending at aright pointer
  13.        """
  14.  
  15.         left = 0
  16.         right = 0
  17.         hashmap = {}
  18.         longestsubstring = 0
  19.  
  20.         while left < len(s) and right < len(s):
  21.             if s[right] in hashmap:
  22.                 del hashmap[s[left]]
  23.                 left += 1
  24.             else:
  25.                 hashmap[s[right]] = right
  26.                 longestsubstring = max(longestsubstring, right-left+1)
  27.                 right += 1
  28.  
  29.         return longestsubstring
  30.  
  31. class Solution:
  32.     def lengthOfLongestSubstring(self, s: str) -> int:
  33.  
  34.         left = 0
  35.         right = 0
  36.         # previously occured index stored here
  37.         hashmap = {}
  38.         longestsubstring = 0
  39.  
  40.         while left < len(s) and right < len(s):
  41.             if s[right] in hashmap and hashmap[s[right]] >= left:
  42.                 # the logic here is a little complex, because we are not deleting it
  43.                 # we need to ensure that the repeated character lied in the given window
  44.                 # between left and right; we need to ensure that left <= hashmap[s[right]] < right
  45.                 left = hashmap[s[right]] + 1
  46.             else:
  47.                 hashmap[s[right]] = right
  48.                 longestsubstring = max(longestsubstring, right-left+1)
  49.                 right += 1
  50.  
  51.         return longestsubstring
  52.            
  53.  
Advertisement
Add Comment
Please, Sign In to add comment