Loading

leetcode#3Longest Substring Without Repeating Characters

 

给定一个字符串,找出不含有重复字符的最长子串的长度。

示例:

给定 “abcabcbb” ,没有重复字符的最长子串是 “abc” ,那么长度就是3。
给定 “bbbbb” ,最长的子串就是 “b” ,长度是1。
给定 “pwwkew” ,最长子串是 “wke” ,长度是3。请注意答案必须是一个子串,”pwke” 是 子序列 而不是子串。

思路:从前向后遍历,并且更新已遍历元素的索引。start是当前序列的起点,当发现当前元素在字典中的索引>start时,意味着出现重复,我们将起点更新为start+1。

持续这个过程直到结束。

class Solution:   
    def lengthOfLongestSubstring(self, s):
        dic, res, start, = {}, 0, 0
        for i, ch in enumerate(s):
            if ch not in dic or (ch in dic and dic[ch]<start):
                res = max(res, i-start+1)
            else:
                start = dic[ch]+1
            dic[ch] = i
        return res

 这里使用了python,因为占了enumerate()这个便宜。

posted @ 2018-09-28 02:47  老鼠阿尔吉侬  阅读(108)  评论(0编辑  收藏  举报