File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ """
3
+ 3. 无重复字符的最长子串
4
+ https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
5
+ 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
6
+ """
7
+ def lengthOfLongestSubstring (self , s : str ):
8
+ n = len (s )
9
+ if n <= 1 :
10
+ return n
11
+
12
+ left = 0
13
+ # 记录集合
14
+ lookup = set ()
15
+ # 最大宽度
16
+ max_len = 0
17
+ # 目前宽度
18
+ cur_len = 0
19
+ for i in range (n ):
20
+ cur_len += 1
21
+ # 如果最新元素在集合中,则必须移除掉该元素
22
+ while s [i ] in lookup :
23
+ # 移除第一次出现新元素之前的元素
24
+ lookup .remove (s [left ])
25
+ left += 1
26
+ cur_len -= 1
27
+
28
+ if cur_len > max_len :
29
+ max_len = cur_len
30
+ lookup .add (s [i ])
31
+ return max_len
32
+
33
+ so = Solution ()
34
+ # 3
35
+ print (so .lengthOfLongestSubstring ('abcabcbb' ))
36
+ # 1
37
+ print (so .lengthOfLongestSubstring ('bbbbb' ))
38
+ # 3
39
+ print (so .lengthOfLongestSubstring ('pwwkew' ))
40
+ # 0
41
+ print (so .lengthOfLongestSubstring ('' ))
You can’t perform that action at this time.
0 commit comments