leetcode(3): Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Analysis

If a repeat char is found, there is no need to search chars before the previous repeat char, so start to search from char after the previous repeat char.

Codes

#!/usr/bin/python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = dict()
        maxLength = 0
        index = 0
        
        while index < len(s):
            if s[index] in d:
                if maxLength < len(d):
                    maxLength = len(d)
                index = d[s[index]] + 1
                d.clear()
            else:
                d[s[index]] = index
                index += 1
                
        if maxLength < len(d):
            maxLength = len(d)
            
        return maxLength
posted @ 2016-01-26 17:11  luckysimple  阅读(169)  评论(0编辑  收藏  举报