My 14 Lines Python O(n) solution


  • 7
    F

    Please feel free to comment if you have any suggestion/question on my code. Thanks.

    class Solution:
        # @param {string} s
        # @return {integer}
        def lengthOfLongestSubstring(self, s):
            start_pos = 0
            current_pos = -1    # consider blank string case
            max_length = 0
            char_pos = {}
            for current_pos in range(len(s)):
                if s[current_pos] in char_pos and char_pos[s[current_pos]] >= start_pos :
                    max_length = max(max_length, current_pos - start_pos)
                    start_pos = char_pos[s[current_pos]] + 1
                char_pos[s[current_pos]] = current_pos
            return max(max_length, current_pos - start_pos + 1)   # consider the no-repeat-char case and last-segment-is-the-longest case

Log in to reply
 

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