Leetcode

3. Longest Substring Without Repeating Characters

Leeter 2021. 10. 15. 03:36

Description:

Given a string s, find the length of the longest substring without repeating characters.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        slow=0
        fast=0
        long=0
        
        map={}
        
        while fast<len(s):
            if s[fast] in map:
                map[s[fast]]+=1
            else:
                map[s[fast]]=1
            
            if map[s[fast]]>1:
                long=max(long,fast-slow)
                
                while map[s[fast]]>1:
                    map[s[slow]]-=1
                    slow+=1
            
            fast+=1
            
        long=max(long,fast-slow)
        
        return long
            
# when n==len(str)
# T/C: O(n)
# S/C: O(n)