-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path3104-find-longest-self-contained-substring.js
More file actions
56 lines (47 loc) · 1.46 KB
/
3104-find-longest-self-contained-substring.js
File metadata and controls
56 lines (47 loc) · 1.46 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
/**
* 3104. Find Longest Self-Contained Substring
* https://leetcode.com/problems/find-longest-self-contained-substring/
* Difficulty: Hard
*
* Given a string s, your task is to find the length of the longest self-contained substring
* of s.
*
* A substring t of a string s is called self-contained if t != s and for every character in
* t, it doesn't exist in the rest of s.
*
* Return the length of the longest self-contained substring of s if it exists, otherwise,
* return -1.
*/
/**
* @param {string} s
* @return {number}
*/
var maxSubstringLength = function(s) {
const firstOccurrences = new Map();
const lastOccurrences = new Map();
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (!firstOccurrences.has(char)) {
firstOccurrences.set(char, i);
lastOccurrences.set(char, i);
} else {
lastOccurrences.set(char, i);
}
}
let result = -1;
for (const [startChar, startIndex] of firstOccurrences) {
const currentStart = startIndex;
let currentEnd = lastOccurrences.get(startChar);
for (let j = currentStart; j < s.length; j++) {
const currentChar = s[j];
if (firstOccurrences.get(currentChar) < currentStart) {
break;
}
currentEnd = Math.max(currentEnd, lastOccurrences.get(currentChar));
if (currentEnd === j && currentEnd - currentStart + 1 !== s.length) {
result = Math.max(result, currentEnd - currentStart + 1);
}
}
}
return result;
};