leetcode算法题(3)--不含重复字符的最长子串长度-Longest Substring Without Repeating Characters

整理自己对一些leetcode算法题的想法和实现,一直努力,每天都有新提高
–来自一个热爱编程的程序媛

1.LeetCode地址:

Longest Substring Without Repeating Characters

2.难度:medium

3.题目:

Given a string, find the length of the longest substring without repeating characters.
leetcode算法题(3)--不含重复字符的最长子串长度-Longest Substring Without Repeating Characters_第1张图片

4.思路

1.字典

想找到最长的子串长度,至少需要记录下已经访问过的字符。如果新来的字符已经在字典中,那么需要把前面的字符去掉,新的加进来,同时计算最大长度。

2.双指针

需要记录下当前探查到的字符位置,也需要记录下当前字典中字符的起始位置,所以要用双指针。

3.图示

i记录左边的位置,j记录右边的位置。max_length返回最大长度。
黄色标志当前的最长子串。绿色表示下一步要探查的j的位置。
图示中,每次删除都是删除i的位置字符,不够快。后面第二种代码有改进。leetcode算法题(3)--不含重复字符的最长子串长度-Longest Substring Without Repeating Characters_第2张图片

5.代码

1.图示思路代码

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        dict_ss ={}
        if len(s) ==0:
            return 0
        maxLen = 0
        i =0
        j=0
        #区间  i  --  j
        while i 

2.改进代码

#Runtime: 52 ms, faster than 98.14% of Python3 online submissions for Longest Substring Without Repeating Characters.
#Memory Usage: 13.4 MB, less than 30.93% of Python3 online submissions for Longest Substring Without Repeating Characters.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        begin_pos =0
        dict_curr={}
        max_length = 0
        curr_length =0
        for i,alpha in enumerate(s):
            if alpha in dict_curr:
            ##不从字典中删除已有字符,只更新位置。每次更新起点为存在字符的下一个位置和上次起点的最大值
                begin_pos = max(dict_curr[alpha]+1,begin_pos)
                dict_curr[alpha] =i
                max_length = max(max_length,curr_length)
                curr_length = i-begin_pos +1
            else:
                dict_curr[alpha] =i
                curr_length +=1
        max_length = max(max_length,curr_length)
        return max_length

你可能感兴趣的:(数据结构和算法,LeetCode)