Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def lengthOfLongestSubstring(self, s: str) -> int:
- """
- At each step, right pointer points to a locations where we
- are trying to calculate length of longest string ending there.
- When we are iterating over the character corresponding to right pointer,
- we might have added one of the duplicate characters already in the hashset
- so we havwe to remove characters from left untill duplicate of s[right] is removed
- Think of it this way:
- how will you calcuate the longest substring ending at aright pointer
- """
- left = 0
- right = 0
- hashmap = {}
- longestsubstring = 0
- while left < len(s) and right < len(s):
- if s[right] in hashmap:
- del hashmap[s[left]]
- left += 1
- else:
- hashmap[s[right]] = right
- longestsubstring = max(longestsubstring, right-left+1)
- right += 1
- return longestsubstring
- class Solution:
- def lengthOfLongestSubstring(self, s: str) -> int:
- left = 0
- right = 0
- # previously occured index stored here
- hashmap = {}
- longestsubstring = 0
- while left < len(s) and right < len(s):
- if s[right] in hashmap and hashmap[s[right]] >= left:
- # the logic here is a little complex, because we are not deleting it
- # we need to ensure that the repeated character lied in the given window
- # between left and right; we need to ensure that left <= hashmap[s[right]] < right
- left = hashmap[s[right]] + 1
- else:
- hashmap[s[right]] = right
- longestsubstring = max(longestsubstring, right-left+1)
- right += 1
- return longestsubstring
Advertisement
Add Comment
Please, Sign In to add comment