Longest Nice Substring LeetCode solution in JavaScript

1
const swapCase = (str) =>
2
str
3
.split("")
4
.map((c) => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()))
5
.join("");
6

7
var longestNiceSubstring = function (s) {
8
let ans = "";
9
for (let i = 0; i < s.length; i++) {
10
for (let ii = i + 1; ii < s.length + 1; ii++) {
11
let substring = s.slice(i, ii); // we take a substring
12

13
let invertedCaseChars = [...substring].map(swapCase); // we create an array of chars from the substring and invert case of this chars
14

15
if (invertedCaseChars.every((char) => substring.includes(char))) {
16
// we check that substring includes every case inverted char (see the illustration above)
17
ans = substring.length > ans.length ? substring : ans; // we select the longest substring which satisfies our condition
18
}
19
}
20
}
21
return ans;
22
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0