-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0003_longest_substring.js
More file actions
30 lines (28 loc) · 914 Bytes
/
0003_longest_substring.js
File metadata and controls
30 lines (28 loc) · 914 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
30
/**
* @link https://leetcode.com/problems/longest-substring-without-repeating-characters/
* @description Return length of longest substring without repetitions
* @param {String} string
* @returns {Number}
*/
export default (string) => {
let sequence = [];
let maxLength = 0;
// Iterate through string
for (let i = 0; i < string.length; i += 1) {
const char = string[i];
// Search index of first occurence in the sequence
const index = sequence.indexOf(char);
sequence.push(char);
// If index is not -1, it means char has already in sequence
if (index !== -1) {
sequence = sequence.slice(index + 1);
}
// Compare current sequence length with max length
// If current one is higher, replace max by current one
const sequenceLength = sequence.length;
if (sequenceLength > maxLength) {
maxLength = sequenceLength;
}
}
return maxLength;
};