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

猜你喜欢

转载自blog.csdn.net/sinat_35815038/article/details/81355396