smj007

Untitled

Jun 19th, 2022
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLongestSubstring(self, s: str) -> int:
  3.        
  4.         # base case
  5.         if not len(s):
  6.             return 0
  7.        
  8.         hashset = set()
  9.        
  10.         left = 0; right = 0
  11.         max_length = 0
  12.  
  13.        
  14.         while(right < len(s)):
  15.            
  16.             if s[right] not in hashset:
  17.                 # keep adding the character untill we find duplicate
  18.                 hashset.add(s[right])
  19.                 max_length = max(max_length, right - left + 1)
  20.                 right += 1
  21.             else:
  22.                 # once duplicate is found, keep removing elements from the left and update
  23.                 # the left pointer untill the repeating character is removed and we have
  24.                 # moved the left pointer to the next element of the duplicate character
  25.                 while(s[right] in hashset):
  26.                     hashset.remove(s[left])
  27.                     left += 1
  28.                    
  29.                 max_length = max(max_length, right - left + 1)
  30.                      
  31.         return max_length
  32.        
  33.        
Advertisement
Add Comment
Please, Sign In to add comment