File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 3. 无重复字符的最长子串
3
+ * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
4
+
5
+ 示例 1:
6
+
7
+ 输入: "abcabcbb"
8
+ 输出: 3
9
+ 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
10
+ 示例 2:
11
+
12
+ 输入: "bbbbb"
13
+ 输出: 1
14
+ 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
15
+ 示例 3:
16
+
17
+ 输入: "pwwkew"
18
+ 输出: 3
19
+ 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
20
+ 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
21
+
22
+ 来源:力扣(LeetCode)
23
+ 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
24
+ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
25
+ */
26
+
27
+ var lengthOfLongestSubstring = function ( str ) {
28
+ if ( str . length === 1 ) {
29
+ return 1
30
+ }
31
+ // 滑动窗口
32
+ var windows = [ 0 , 0 ]
33
+ var max = 0
34
+
35
+ // 出现过的字符保存在set中 便于匹配是否出现过此字符串
36
+ var set = new Set ( )
37
+ for ( var i = 0 ; i < str . length ; i ++ ) {
38
+ var char = str [ i ]
39
+
40
+ // 如果匹配过了这个字符 窗口左边界+1
41
+ if ( set . has ( char ) ) {
42
+ windows [ 0 ] ++
43
+ }
44
+
45
+ // 右边界一直后移
46
+ windows [ 1 ] ++
47
+
48
+ var windowsLength = windows [ 1 ] - windows [ 0 ]
49
+ if ( windowsLength > max ) {
50
+ max = windowsLength
51
+ }
52
+ set . add ( char )
53
+ }
54
+
55
+ return max
56
+ }
57
+ console . log ( lengthOfLongestSubstring ( "abcabcbb" ) )
You can’t perform that action at this time.
0 commit comments