Skip to content

Commit 007561b

Browse files
committed
feat: add solution for Longest Substring Without Repeating Characters
1 parent cc875d6 commit 007561b

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

javascript/3-Longest-Substring-Without-Repeating-Characters.js

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,54 @@ var lengthOfLongestSubstring = function (str) {
1919
max = Math.max(max, i - start + 1);
2020
}
2121
return max;
22-
};
22+
};
23+
24+
25+
/**
26+
* @param {string} str
27+
* @return {number}
28+
*/
29+
var lengthOfLongestSubstring = function(str) {
30+
31+
let set = new Set()
32+
let max = 0;
33+
34+
let firstLetterTracker = 0
35+
for(let i = 0; i < str.length; i++) {
36+
const letter = str[i]
37+
38+
while(set.has(letter)){
39+
const firstLetter = str[firstLetterTracker]
40+
set.delete(firstLetter)
41+
firstLetterTracker++
42+
}
43+
44+
set.add(letter)
45+
46+
max = Math.max(max,i - firstLetterTracker + 1)
47+
}
48+
49+
return max;
50+
};
51+
52+
53+
/**
54+
* @param {string} str
55+
* @return {number}
56+
*/
57+
var lengthOfLongestSubstring = function(str) {
58+
let windowStart = 0, maxLength = 0, charIndexMap = {};
59+
60+
for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
61+
const rightChar = str[windowEnd];
62+
63+
if (rightChar in charIndexMap) {
64+
windowStart = Math.max(windowStart, charIndexMap[rightChar] + 1);
65+
}
66+
67+
charIndexMap[rightChar] = windowEnd;
68+
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
69+
}
70+
71+
return maxLength;
72+
}

0 commit comments

Comments
 (0)