leetcode -- Longest Substring Without Repeating Characters -- 简单要知道思路

来源:互联网 发布:淘宝有意思的店铺 编辑:程序博客网 时间:2024/06/07 03:06

https://leetcode.com/problems/longest-substring-without-repeating-characters/

思路参考http://www.cnblogs.com/zuoyuan/p/3785840.html

用双指针i,j. i是substring的开头,j是substring的结尾。i固定,用j来往后scan。边scan边update 哈希表,知道j遇到一个重复的字母,然后从哈希表中获取此重复值在substring的index,然后删除哈希表中index之前的所有元素。更新这个重复字母的哈希值为j,更新i为index +1.一直到j == len(s).期间注意给maxlen赋值。
这里其实也可以不用哈希表,用一个string就可以了

还要注意最后j == lens(s)跳出while循环之后,还要做一次与maxlen的判断。例如s = ‘abc’

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        mydict = {}        maxlen = -1        i,j = 0,0        while j< len(s):            if s[j] not in mydict:                mydict[s[j]] = j            else:                maxlen = max(j - i, maxlen)                ind = mydict[s[j]]                mydict[s[j]] = j                for k in xrange(i, ind):                    del mydict[s[k]]                i = ind + 1            j += 1        maxlen = max(j - i, maxlen)        return maxlen
0 0
原创粉丝点击