|
| 1 | +/** |
| 2 | + * @param {string} s Input string. |
| 3 | + * @return {number} Length of longest substring without repeating characters. |
| 4 | + * @summary Longest Substring Without Repeating Characters {@link https://leetcode.com/problems/longest-substring-without-repeating-characters/} |
| 5 | + * @description Given a string, find length of its longest substring without repeating characters. |
| 6 | + * Space O(n) - hash object storing data will have no more than n elements. |
| 7 | + * Time O(n) - one iteration of n elements. |
| 8 | + */ |
1 | 9 | const lengthOfLongestSubstring = s => {
|
2 | | - letlongest = 0, |
3 | | - current= 0, |
4 | | - hashMap={}; |
| 10 | + constcharMap = {}; |
| 11 | + letmaxLength= 0; |
| 12 | + letcurrentStart=0; |
5 | 13 |
|
6 | 14 | for (let index = 0; index < s.length; index++) {
|
7 | | - if (!hashMap[s[index]]) { |
8 | | - hashMap[s[index]] = true; |
9 | | - current++; |
10 | | - } else { |
11 | | - if (current > longest) { |
12 | | - longest = current; |
13 | | - } |
| 15 | + const c = s[index]; |
14 | 16 |
|
15 | | - current=0; |
16 | | - index--; |
17 | | - hashMap = {}; |
| 17 | + if(charMap[c]!==undefined&&charMap[c]>=currentStart){ |
| 18 | + maxLength=Math.max(maxLength,index-currentStart); |
| 19 | + currentStart = charMap[c]+1; |
18 | 20 | }
|
19 | 21 |
|
20 | | - if (current > longest) { |
21 | | - longest = current; |
22 | | - } |
| 22 | + charMap[c] = index; |
23 | 23 | }
|
24 | 24 |
|
25 | | - return longest; |
| 25 | + return Math.max(maxLength,s.length-currentStart); |
26 | 26 | };
|
0 commit comments