Leetcode -- Python -- 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.

分析:

此题应用two pointers的方法。 1. abcdbef  注意如果遇到相同的字母,具体来说,此时p1-> "a",  p2 ->"d" ,那么下一步p2+1,则p2 ->"b",所以遇到相同的字母了,那么p1应该调到p1 ->"c".(b之后的位置)。

此外,还应该熟悉函数,Python函数find(value) == 找到对应的值在string中的index

另外,max_l计算的方法,还有method 2,不过道理都是一样的,只是计算max的时机不一样。


Python 代码:

<pre name="code" class="python">class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        if s == None:
            return 0
        p1 = 0
        p2 = 0
        l = len(s)
        max_l = 0
        while l > p2 :
            if s[p2] not in s[p1:p2]:
                max_l = max(max_l, p2 - p1 +1)
                p2 = p2 + 1
            else:
                # method 2 -- max_l = max(max_l, p2 - p1)
                p1 = p1 + s[p1:p2].find(s[p2]) + 1
                p2 = p2 + 1
                
        # method 2 -- max_l = max(max_l, p2 - p1)
        return max_l


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值