2 Way in Python, list and defaultdict


  • 0
    L
    def lengthOfLongestSubstring_list(self, s):
        start, maxlen = 0, 0
        alphabet = [0]*128
        for i, char in enumerate(s):
            charidx = ord(char)
            if alphabet[charidx] > start:
                maxlen = max(maxlen, i-start)
                start = alphabet[charidx]
            alphabet[charidx] = i+1
        return max(maxlen, len(s) - start)
    
    def lengthOfLongestSubstring_dict(self, s):
        start, maxlen =0, 0
        alphabet = defaultdict(int)
        for i, char in enumerate(s):
            if alphabet[char] > start:
                maxlen = max(maxlen, i-start)
                start = alphabet[char]
            alphabet[char] = i+1
        return max(maxlen, len(s) - start)

Log in to reply
 

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