-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalternate-regex.js
More file actions
37 lines (25 loc) · 1.31 KB
/
alternate-regex.js
File metadata and controls
37 lines (25 loc) · 1.31 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
function alternate(s) {
let maxlen = 0;
const combinations = [];
[...new Set(s)].forEach((v, i, a) => {
a.slice(i + 1).forEach(v1 => {
combinations.push([v, v1]);
})
});
combinations.forEach(comb => {
let t = [...s].filter(v => comb.includes(v)).join('');
if (t.match(/(.)\1/) === null) {
maxlen = Math.max(maxlen, t.length)
}
})
return maxlen;
}
// Explanation:
// A) get a set of unique letters in the string
// B) build an array of all 2 letter combinations from that set
// C) go through those combinations one at a time, building a new string that only consists of those 2 letters
// D) use a regex to see if there are any consecutive matching letters, e.g. aa. If there are then it isn't an alternating string
// E) if it is an alternating string, then update the max length found if it is longer
// (.) matches any character (the dot) and captures it (the brackets). This capture can be used later in the regexp by referring to \1 (backreference capture number one).
// So this regexp matches any character that is immediately followed by the same character, e.g. aa, bb, cc, but not xy
// If the output of that match is null then there are no duplicate characters like that, which therefore means the characters must be alternating.