Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c11cd46

Browse files
committed
fix: leetcode-3
1 parent 40b1f37 commit c11cd46

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

length-of-longest-substring-3.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
2424
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2525
*/
26-
2726
var lengthOfLongestSubstring = function(str) {
2827
if (str.length === 1) {
2928
return 1
@@ -32,24 +31,26 @@ var lengthOfLongestSubstring = function(str) {
3231
var windows = [0, 0]
3332
var max = 0
3433

35-
// 出现过的字符保存在set中 便于匹配是否出现过此字符串
36-
var set = new Set()
3734
for (var i = 0; i < str.length; i++) {
3835
var char = str[i]
3936

40-
// 如果匹配过了这个字符 窗口左边界+1
41-
if (set.has(char)) {
42-
windows[0]++
37+
// 当前窗口中的文字
38+
var windowsStr = str.substring(windows[0], windows[1])
39+
40+
// 窗口中如果已经出现了这个文字 就需要把窗口左侧移动到「上一次出现这个文字」的右边位置
41+
var windowsCharIdx = windowsStr.indexOf(char)
42+
if (windowsCharIdx !== -1) {
43+
// 注意要加上窗口左侧已经移动的距离
44+
windows[0] += windowsCharIdx + 1
4345
}
4446

45-
// 右边界一直后移
47+
// 右边界始终后移
4648
windows[1]++
4749

4850
var windowsLength = windows[1] - windows[0]
4951
if (windowsLength > max) {
5052
max = windowsLength
5153
}
52-
set.add(char)
5354
}
5455

5556
return max

0 commit comments

Comments
 (0)