[leetcode]Longest Substring Without Repeating Characters(using python)

原题链接:点击打开链接

题目:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

解题思路:

刚开始的时候用一个字典配合一个列表做,用列表保存每轮找到的最长的string,当遇到重复的字符时,到字典中查找重复字符先前出现的位置,之后再将curpoint指针指到那个字符的后面一位重新开始。举个栗子,比如“dvdf”这个字符串,当顺序读到第二次出现的d是,字典中内容为{d:0,v:1},可以查到之前出现的d的位置为0,于是将curpoint置为1,即从v开始重新查找。

但是在提交时发现,有一个用例测试不通过,原因是运行超时。分析上面的做法可知上面描述的算法中做了很多重复的工作。进一步改进的做法是不再使用列表,而只用一个字典做,每次的删除工作直接在字典上进行,可以有效避免重复工作,

AC代码如下:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        curpoint = 0
        llen = 0
        popkey_list = []
        detect_repeat = {}
        while curpoint < len(s):
            if s[curpoint] in detect_repeat:
                if len(detect_repeat.keys()) > llen:
                    llen = len(detect_repeat.keys())
                for key,value in detect_repeat.iteritems():
                    if value <= detect_repeat[s[curpoint]]:
                        popkey_list.append(key)
                for key in popkey_list:        
                    detect_repeat.pop(key)
                popkey_list = []
            detect_repeat[s[curpoint]] = curpoint
            curpoint += 1
        if len(detect_repeat.keys()) > llen:
            llen = len(detect_repeat.keys())
        return llen


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值