码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode(3): Longest Substring Without Repeating Characters

时间:2016-01-26 18:38:48      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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

leetcode(3): Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/luckysimple/p/5161026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!