-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlengthOfLongestSubstring.js
49 lines (46 loc) · 1.2 KB
/
lengthOfLongestSubstring.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
* @Author: Z1hgq
* @Date: 2019-09-17 14:26:50
* @LastEditTime: 2019-09-17 18:07:46
*/
/**
* @param {string} s
* @return {number}
*/
const lengthOfLongestSubstring = function (s) {
let res = 0;
let i = 0;
const temp = [];
while (i < s.length) {
if (temp.indexOf(s[i]) === -1) { // 如果不存在的话向数组里继续添加
temp.push(s[i]);
} else {
temp.shift(); // 如果存在的话表明当前这个子串不符合无重复字符的要求,删除队头的元素,跳出这次循环
continue;
}
res = Math.max(res, temp.length);
i++;
}
return res;
};
// 超时
const lengthOfLongestSubstringII = function (s) {
if (s === "") return 0;
for (let i = s.length; i > 0; i--) {
let j = 0;
while (j + i <= s.length) {
const str = s.slice(j, j + i);
if (s.indexOf(str) != -1) {
const strSet = new Set(str);
if (Array.from(strSet).length === str.length) {
return str.length;
} else {
j++;
}
} else {
j++;
}
}
}
};
console.log(lengthOfLongestSubstring("dvuadbiabkhbcacbnaosbduioheqwoehoiqwjojojaddddddddddddddohwdoboubqibibiuabisbdoahdiqowhdpqwpojlcnklasnclknalkdf"));