Leetcode题解之 —— 无重复字符的最长子串

思路


暴力解法

  • 空字判断
  • 连续字串
  • 及时更新新的子串数组
  • 更新max

题解


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
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
const len = s.length;
let [max, count, cache] = [1, 0, []];

if (!s) {
return 0;
}

while (count < len) {
const current = s[count];

if(cache.includes(current)) {
const finalIndex = cache.lastIndexOf(current);
const filteredCache = cache.slice(finalIndex + 1);
cache = [...filteredCache, current];
}else {
cache.push(current);
}

max = Math.max(cache.length, max);

count++;
}

return max;
};