1
1
## 题目地址
2
+
2
3
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
3
4
4
5
## 题目描述
6
+
5
7
Given a string, find the length of the longest substring without repeating characters.
6
8
7
9
Examples:
10
+
8
11
```
9
12
Given "abcabcbb", the answer is "abc", which the length is 3.
10
13
11
14
Given "bbbbb", the answer is "b", with the length of 1.
12
15
13
16
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.
14
17
```
18
+
15
19
## 思路
16
20
17
- 用一个hashmap来建立字符和其出现位置之间的映射 。
21
+ 用一个 hashmap 来建立字符和其出现位置之间的映射 。
18
22
19
23
维护一个滑动窗口,窗口内的都是没有重复的字符,去尽可能的扩大窗口的大小,窗口不停的向右滑动。
20
24
@@ -24,19 +28,24 @@ Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer
24
28
25
29
(3)重复(1)(2),直到左边索引无法再移动;
26
30
27
- (4)维护一个结果res,每次用出现过的窗口大小来更新结果res,最后返回res获取结果 。
31
+ (4)维护一个结果 res,每次用出现过的窗口大小来更新结果 res,最后返回 res 获取结果 。
28
32
29
33
![ 3.longestSubstringWithoutRepeatingCharacters] ( ../assets/3.longestSubstringWithoutRepeatingCharacters.gif )
30
34
31
35
(图片来自: https://github.com/MisterBooo/LeetCodeAnimation )
32
36
33
37
## 关键点
34
38
35
- 1 . 用一个mapper记录出现过并且没有被删除的字符
36
- 2 . 用一个滑动窗口记录当前index开始的最大的不重复的字符序列
37
- 3 . 用res去记录目前位置最大的长度,每次滑动窗口更新就去决定是否需要更新res
39
+ 1 . 用一个 mapper 记录出现过并且没有被删除的字符
40
+ 2 . 用一个滑动窗口记录当前 index 开始的最大的不重复的字符序列
41
+ 3 . 用 res 去记录目前位置最大的长度,每次滑动窗口更新就去决定是否需要更新 res
38
42
39
43
## 代码
44
+
45
+ 代码支持:JavaScript,Python3
46
+
47
+ JavaScript Code:
48
+
40
49
``` js
41
50
/**
42
51
* @param {string} s
@@ -53,7 +62,7 @@ var lengthOfLongestSubstring = function(s) {
53
62
// 则删除
54
63
const delIndex = slidingWindow .findIndex (_c => _c === c);
55
64
56
- for (let i = 0 ; i < delIndex; i++ ) {
65
+ for (let i = 0 ; i < delIndex; i++ ) {
57
66
mapper[slidingWindow[i]] = false ;
58
67
}
59
68
@@ -69,3 +78,25 @@ var lengthOfLongestSubstring = function(s) {
69
78
return res;
70
79
};
71
80
```
81
+
82
+ Python3 Code:
83
+
84
+ ``` python
85
+ from collections import defaultdict
86
+
87
+
88
+ class Solution :
89
+ def lengthOfLongestSubstring (self , s : str ) -> int :
90
+ l = 0
91
+ ans = 0
92
+ counter = defaultdict(lambda : 0 )
93
+
94
+ for r in range (len (s)):
95
+ while counter.get(s[r], 0 ) != 0 :
96
+ counter[s[l]] = counter.get(s[l], 0 ) - 1
97
+ l += 1
98
+ counter[s[r]] += 1
99
+ ans = max (ans, r - l + 1 )
100
+
101
+ return ans
102
+ ```
0 commit comments