Python hash+2pt beats 90%


  • 0
    A
    '''
    Given a string, find the length of the longest substring without repeating characters.
    
    Examples:
    
    Given "abcabcbb", the answer is "abc", which the length is 3.
    
    Given "bbbbb", the answer is "b", with the length of 1.
    
    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
    '''
    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            if not s:
                return 0
            if len(s)==1:
                return 1
            dic={s[0]:0}
            lf,rt=0,0
            _max=0
            while rt+1<len(s):
                rt+=1
                if s[rt] not in dic:
                    dic[s[rt]]=rt
                else:
                    if lf<=dic[s[rt]]:
                        lf=dic[s[rt]]+1
                        dic[s[rt]]=rt
                    else:
                        dic[s[rt]]=rt
                if rt-lf+1>_max:
                    _max=rt-lf+1
            return _max
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.