【LeetCode刷题之旅】Longest Substring Without Repeating Characters【Python】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38371360/article/details/86485345

题目描述:

给定一个字符串,请你找出其中不含有重复字符的 最长子串 (连续的)的长度。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        length_this = 0
        length_max = 0
        if s is None or len(s) == 0:
            return length_max
        start = 0
        dictionary = {}
        for i in range(len(s)):
            cur = s[i]
            if cur in dictionary and dictionary[cur] >= start:
                start = dictionary[cur] + 1
            length_this = i - start + 1
            dictionary[cur] = i
            length_max = max(length_max,length_this)
        return length_max

 步骤

  1. 初始化历史最长子串长度和本次循环最长子串长度
  2. 判断传入的字符串是否为空,如果为空则返回长度为0
  3. 初始化一个哈希表(字典)
  4. 用cur变量遍历s字符串,对每一个字符进行如下操作:
  • 查询当前cur变量是否在哈希表的键中且此时cur的位置是否大于start()
  • 如果满足上述条件,则将start移动到dictionary[cur]的后一位,保证cur继续向后遍历时,从start到cur没有重复元素。
  • 如果不满足则在dictionary中记录键值对(当前字符cur,当前位置i),计算本次循环最大子串长度length_this,利用max函数比较length_max和length_this的大小并将大的那个赋值给length_max

猜你喜欢

转载自blog.csdn.net/weixin_38371360/article/details/86485345