11## 题目地址
2+
23https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
34
45## 题目描述
6+
57Given a string, find the length of the longest substring without repeating characters.
68
79Examples:
10+
811```
912Given "abcabcbb", the answer is "abc", which the length is 3.
1013
1114Given "bbbbb", the answer is "b", with the length of 1.
1215
1316Given "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.
1417```
18+
1519## 思路
1620
17- 用一个hashmap来建立字符和其出现位置之间的映射 。
21+ 用一个 hashmap 来建立字符和其出现位置之间的映射 。
1822
1923维护一个滑动窗口,窗口内的都是没有重复的字符,去尽可能的扩大窗口的大小,窗口不停的向右滑动。
2024
@@ -24,19 +28,24 @@ Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer
2428
2529(3)重复(1)(2),直到左边索引无法再移动;
2630
27- (4)维护一个结果res,每次用出现过的窗口大小来更新结果res,最后返回res获取结果 。
31+ (4)维护一个结果 res,每次用出现过的窗口大小来更新结果 res,最后返回 res 获取结果 。
2832
2933![ 3.longestSubstringWithoutRepeatingCharacters] ( ../assets/3.longestSubstringWithoutRepeatingCharacters.gif )
3034
3135(图片来自: https://github.com/MisterBooo/LeetCodeAnimation )
3236
3337## 关键点
3438
35- 1 . 用一个mapper记录出现过并且没有被删除的字符
36- 2 . 用一个滑动窗口记录当前index开始的最大的不重复的字符序列
37- 3 . 用res去记录目前位置最大的长度,每次滑动窗口更新就去决定是否需要更新res
39+ 1 . 用一个 mapper 记录出现过并且没有被删除的字符
40+ 2 . 用一个滑动窗口记录当前 index 开始的最大的不重复的字符序列
41+ 3 . 用 res 去记录目前位置最大的长度,每次滑动窗口更新就去决定是否需要更新 res
3842
3943## 代码
44+
45+ 代码支持:JavaScript,Python3
46+
47+ JavaScript Code:
48+
4049``` js
4150/**
4251 * @param {string} s
@@ -53,7 +62,7 @@ var lengthOfLongestSubstring = function(s) {
5362 // 则删除
5463 const delIndex = slidingWindow .findIndex (_c => _c === c);
5564
56- for (let i = 0 ; i < delIndex; i++ ) {
65+ for (let i = 0 ; i < delIndex; i++ ) {
5766 mapper[slidingWindow[i]] = false ;
5867 }
5968
@@ -69,3 +78,25 @@ var lengthOfLongestSubstring = function(s) {
6978 return res;
7079};
7180```
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