Advertisement
smj007

Untitled

Aug 3rd, 2023
1,133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 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 have 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.         hashset = set()
  17.         ans = 0
  18.  
  19.         for right in range(len(s)):
  20.             while(s[right] in hashset):
  21.                 hashset.remove(s[left])
  22.                 left=left+1
  23.  
  24.             hashset.add(s[right])
  25.             ans = max(ans, right - left + 1)
  26.  
  27.         return ans
  28.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement