LeetCode-最长没有重复元素的子串——D5【一般难度】

题目描述

3.longestSubstringWithoutRepeatingCharacters
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

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.

算法思路

1)设置longest存储最终最长的子串,temp存储当前正在遍历的子串
2)设置左右指针,如果下一个元素与当前temp中元素没有重复,则移动右指针;否则移动做指针,再将右指针所指元素与test中元素比较。重复此步骤。
3)每当遇到右指针所指元素存在于当前temp中,则需要将当前temp长度和longest长度进行比较,决定是否更新longest

算法实现

def longestSubstringWithoutRepeatingCharacters(s):
    left=0
    right=1
    longest=[]
    temp=[]
    
    if len(s)==1:
        longest = s
    
    temp.append(s[0])
    while(left<len(s)-1):
        #右指针所指元素已经存在
        if s[right] in temp:
            #判定是否为最长子串
            if len(temp)>len(longest):
                longest=temp[:]
                
            #左指针指向元素左移
            temp.pop(0)
            left+=1
        
        #右指针所指元素还不存在
        else:
            temp.append(s[right])
            if right<len(s)-1:
                right+=1
            
        print("left:%d,right:%d,temp:%s,longest:%s"%(left,right,temp,longest))
    return longest
print(longestSubstringWithoutRepeatingCharacters(list("bbbbbbabcabcbb")))    

小知识点总结

  1. python中list的拷贝方式:
import copy
 
a = [[1,2],10,20]
a1 = a  #第1种
a2 = a[:]  #第2种
a3 = list(a)  #第3种
a4 = a*1  #第4种
a5 = copy.copy(a)  #第5种
a6 = [x for x in a]  #第6种
a7 = copy.deepcopy(a)  #第7种
 
a.append(30)
a[0].append(3)
 
print('a:',a)
print('a1:',a1)
print('a2:',a2)
print('a3:',a3)
print('a4:',a4)
print('a5:',a5)
print('a6:',a6)
print('a7:',a7)

输出为:

a: [[1, 2, 3], 10, 20, 30]
a1: [[1, 2, 3], 10, 20, 30]
a2: [[1, 2, 3], 10, 20]
a3: [[1, 2, 3], 10, 20]
a4: [[1, 2, 3], 10, 20]
a5: [[1, 2, 3], 10, 20]
a6: [[1, 2, 3], 10, 20]
a7: [[1, 2], 10, 20]

a1 = a 表示 a1 和 a 指向同一个内存地址,只是名称不同。

a2~a6 则是指向不同的列表,因为创建新的列表,所以原列表发生改变时,拷贝列表不变,但是里面元素本身的地址并没有改变,所以如果子元素为列表时,子元素列表在拷贝时地址并不会发生变化,所以当原列表中子列表发生改变时,拷贝列表同样会发生改变。

a7 是深度拷贝,所以无论列表中嵌套了几层列表,拷贝列表都不会随着原列表的改变而改变。

  1. Spyder中的快速缩进方法
  • 往右移动4格
    先鼠标选中要移动的多行代码,然后按tab建,按一次移动4格

  • 往左边移动
    同样选中多行,然后按shift+tab移动

发布了205 篇原创文章 · 获赞 655 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/qq_33414271/article/details/97570040