File tree Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Original file line number Diff line number Diff line change 2323 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
2424 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2525*/
26-
2726var 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
You can’t perform that action at this time.
0 commit comments