forked from HudsonAdjetey/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestString.js
More file actions
29 lines (26 loc) · 820 Bytes
/
LongestString.js
File metadata and controls
29 lines (26 loc) · 820 Bytes
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
/*
#PROBLEM#
Given a string s, find the length of the longest
substring
without repeating characters.
*/
/* SOLUTION */
const lengthOfLongestSubstring = (str) => {
// Map to store chars and their indexes
const charIndexMap = new Map()
let maxLength = 0
let start = 0
// loop through using the trasverseMethod
for(let end = 0; end < str.length; end++){
const currentChar = str[end]
if(charIndexMap.has(currentChar)){
// update start if necessary
start = Math.max(start, charIndexMap.get(currentChar)+1)
}
// update map with the current index
charIndexMap.set(currentChar, end)
// check if we have a longer substring than before
maxLength = Math.max(maxLength, end-start+1)
}
return maxLength
}