leetcode 学习笔记

#leetcode problem
The problem is :
3. Longest Substring Without Repeating Characters
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.

方法一:
思路比较简单,采用类似队列的思想,每遇到一个新的字母,就将其加入队列,如果当前字母已在队列中,则先不放入队列,计算此时队列中字母的长度,可以用len()函数来计算,然后max比较。接着,把重复字母包括它之前的字母,全部扔出队列。然后继续放入字母,重复上述步骤。

Python代码如下:

	  sub = []
      maxl = 0
       for i in s:
           if i not in sub:
               sub.append(i)
           else:
               maxl = max(maxl,len(sub))
               for j in range(sub.index(i)+1):
                   sub.pop(0)
               sub.append(i)
       maxl = max(maxl,len(sub))
       return maxl

方法二:
思路类似指针。用两个指针,左和右。一开始左右两指针都指向字符串的-1位置,然后随着for循环的进行,右指针时刻指向目前的最新字母,如果没有重复字母,则继续前进,遇到重复字母时,左指针指向重复字母,然后计算长度。注意,左指针也只能前进,不许后退。所以,如果重复字母的下标小于小于左指针,即重复字母在上次的重复字母之前,那么不能更新和计算长度。
同时,为了涵盖所有情况,在没有遇到重复字母时,也要每次都计算一下当前的可用长度。
Python代码如下:

        left_point = -1
        right_point = -1
        dic = {}
        maxl = 0
        for i in s:
            right_point += 1
            if i not in dic:
                dic[i] = right_point
                maxl = max(maxl,right_point - left_point)
            else:
                if dic[i]>left_point:   # promise that the left point move forward ,instead of moving back
                    left_point = dic[i]
                dic[i] = right_point
                maxl = max(maxl,right_point - left_point)
        return maxl

不过,我的代码不够简洁,学习了一下大牛的算法,移植后的简洁版本如下:

# ----a very concise solution----
        maxlen = 0
        start = -1
        count = -1
        dic = {}
        for i in s:
            count +=1
            if i in dic and dic[i]>start:
                start = dic[i]
            dic[i] = count
            maxlen = max(maxlen,count-start)
        return maxlen

我的个人博客

欢迎大家访问我搭建的个人博客哦,通过github Page搭建的,基于hexo,用了next主题。有什么问题都可以互相交流。博客地址:我的个人博客:CodeSausage的博客

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值