提取最长且不重复的子串

Given "abcabcbb", the answer is "abc".

分析:

根据子串的结构, 循环遍历原始串str, 保存非重复且当前长度最长的子串new_str.


例如, 当指针指向str的 i 位置, 判断当前位置的字符是否在new_str中出现过,若没有,当前new_str长度加一,并将i位置的字符放入new_str中,

如若有, new_str中出现该字符的位置以后的子串作为新子串new_str, 同样将i位置的字符加入new_str, 直到结束.


转自leetcode上的代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        new_str = ''
        max = 0
        for ch in s:
            if not ch in new_str:
                new_str += ch
            else:
                max = len(new_str) if len(new_str) > max else max
                idx = new_str.find(ch)
                new_str = new_str[idx+1:] + ch
        max = len(new_str) if len(new_str) > max else max
        return max



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值