forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthofLongestSubstringWithoutRepetition.js
More file actions
Latest commit
27 lines (25 loc) · 935 Bytes
/
Copy pathLengthofLongestSubstringWithoutRepetition.js
File metadata and controls
27 lines (25 loc) · 935 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
/*
* @description : Given a string, the function finds the length of the longest substring without any repeating characters
* @param {String} str - The input string
* @returns {Number} The Length of the longest substring in a given string without repeating characters
* @example lengthOfLongestSubstring("abcabcbb") => 3
* @example lengthOfLongestSubstring("bbbbb") => 1
* @see https://leetcode.com/problems/longest-substring-without-repeating-characters/
*/
constlengthOfLongestSubstring=(s)=>{
if(typeofs!=='string'){
thrownewTypeError('Invalid Input Type')
}
letmaxLength=0
letstart=0
constcharMap=newMap()
for(letend=0;end<s.length;end++){
if(charMap.has(s[end])){
start=Math.max(start,charMap.get(s[end])+1)
}
charMap.set(s[end],end)
maxLength=Math.max(maxLength,end-start+1)
}
returnmaxLength
}
export{lengthOfLongestSubstring}