LeetCode #3: Longest Substring Without Repeating Characters
β’ 111 words β’ 1 min β’ updated
LeetCode #3: Longest Substring Without Repeating Characters:
A set is enough but we could also employ a Counter or a dict.
python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
v = set()
left = right = 0
ans = 0
while right < len(s):
while s[right] in v:
v.remove(s[left])
left += 1
v.add(s[right])
ans = max(ans, right - left + 1)
right += 1
return ansBetter:
python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
v = set()
left = right = 0
ans = 0
for right in range(len(s)):
while s[right] in v:
v.remove(s[left])
left += 1
v.add(s[right])
ans = max(ans, right - left + 1)
return ans