Skip to content

Instantly share code, notes, and snippets.

@Shikkic
Last active January 6, 2017 18:22
Show Gist options
  • Save Shikkic/dadec85968b951bb7e03d55c33136ead to your computer and use it in GitHub Desktop.
Save Shikkic/dadec85968b951bb7e03d55c33136ead to your computer and use it in GitHub Desktop.
longest_substring_problem
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        if len(s) == 0: return 0
        
        if len(s) == 1: return 1
        
        m = {}
        max_len = 0
        
        # Left pointer represents the most left position of our string.
        left_pointer = 0
        
        # Iterate over every char in the string we're given.
        for right_pointer, char in enumerate(s):
            # If we already have this character in our map, we need to
            # move our left_pointer to be 1 past the positon of that
            # char in our string.
            if m.get(char):
                # Set the pointer to be the max of itself, or the position of the duplicate character plus 1.
                left_pointer = max(left_pointer, m.get(char) + 1)

            # Set the maping of the 'char` we're on, to its index value.
            m[char] = right_pointer
            
            # Set the new current maximum to be the difference between
            # left_pointer and right_pointer. Plus 1 to make up for length
            # difference.
            current_max = (right_pointer - left_pointer) + 1
            
            # Set the new max_len only if the current_max is greater.
            max_len = max(current_max, max_len)
            
        return max_len
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment