-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathlongestSubstringWithoutRepeatingChars.js
More file actions
64 lines (59 loc) · 1.4 KB
/
longestSubstringWithoutRepeatingChars.js
File metadata and controls
64 lines (59 loc) · 1.4 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Sliding window: TC: O(n), SC: O(min(n, m))
/**
* Finds the length of the longest substring without repeating characters.
* @param {string} str
* @returns {number} Length of the longest substring without repeating characters.
*/
function longestSubstringLengthWithoutRepeatingChar(str) {
let charSet = new Set();
let left = 0,
right = 0,
maxLength = 0;
while (right < str.length) {
while (charSet.has(str[right])) {
charSet.delete(str[left]);
left++;
}
charSet.add(str[right]);
right++;
maxLength = Math.max(maxLength, charSet.size);
}
return maxLength;
}
//Additional problem
function longestSubstringWithoutRepeatingChar(str) {
let charSet = new Set();
let left = 0,
right = 0,
start = 0,
maxLength = 0;
while (right < str.length) {
while (charSet.has(str[right])) {
charSet.delete(str[left]);
left++;
}
charSet.add(str[right]);
right++;
if (charSet.size > maxLength) {
start = left;
maxLength = charSet.size;
}
}
return str.substring(start, start + maxLength);
}
// Test cases
const testStrings = [
"abcabcbbaa", // 3
"aaaaaaa", // 1
"pwwkew", // 3
"dvdf", // 3
"", // 0
"abcdef", // 6
];
for (const s of testStrings) {
console.log(
`Input: "${s}" | Length: ${longestSubstringLengthWithoutRepeatingChar(
s
)} | Substring: "${longestSubstringWithoutRepeatingChar(s)}"`
);
}