标签:must for 搜索 ant pre font 比较 enumerate +=
Given a string, find the length of the longest substring without repeating characters.
Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc"
, with the length of 3.
Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b"
, with the length of
Example 3: Input: "pwwkew" Output: 3 Explanation: 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 class Solution(object):
2 def lengthOfLongestSubstring(self, s):
3 """
4 :type s: str
5 :rtype: int
6 """
7 if len(s) < 2:
8 return 1 if len(s) == 1 else 0
9 index, max_count = 0, 0 # 设置标志量和最大长不重复字段的数目
10 tem_dict, count = {}, 0 # 设置辅助空间字典和当前的技术器
11 for i, char in enumerate(s): # 冲头开始遍历
12 if char in tem_dict and tem_dict[char] >= index: # 如果当前字符在字典中并且字典中的下标大于等于标志量下标(标志量表示从哪一个字符开始计算的)
13 max_count =max(count,max_count) # 求出最大的数
14 count = i - tem_dict[char] # 算出第一个出现重复的字符串当第二次出现时的距离数。
15 index = tem_dict[char]+1 # 将标志量设置到第一次出现重复字符串的下一个。
16 else:
17 count += 1 # 无重复字符出现,计数加1
18 tem_dict[char] = i # 记录当前字符串下标
19 return max(count, max_count) # 返回最大的距离数
【LeetCode每天一题】Longest Substring Without Repeating Characters(最长无重复的字串)
标签:must for 搜索 ant pre font 比较 enumerate +=
原文地址:https://www.cnblogs.com/GoodRnne/p/10606662.html