1
var restoreIpAddresses = function (s) {
2
const results = [];
3

4
const go = (str, arr) => {
5
// if we used every character and have 4 sections, it's a good IP!
6
if (str.length === 0 && arr.length === 4) {
7
results.push(arr.join("."));
8
return;
9
}
10
// we already have too many in the array, let's just stop
11
if (arr.length >= 4) {
12
return;
13
}
14
// chop off next 3 characters and continue recursing
15
if (
16
str.length > 2 &&
17
+str.substring(0, 3) < 256 &&
18
+str.substring(0, 3) > 0 &&
19
str[0] !== "0"
20
) {
21
go(str.slice(3), [...arr, str.substring(0, 3)]);
22
}
23
// chop off next 2 characters and continue recursing
24
if (str.length > 1 && +str.substring(0, 2) > 0 && str[0] !== "0") {
25
go(str.slice(2), [...arr, str.substring(0, 2)]);
26
}
27
// chop off next 1 character and continue recursing, in this case, starting with 0 is OK
28
if (str.length > 0 && +str.substring(0, 1) >= 0) {
29
go(str.slice(1), [...arr, str.substring(0, 1)]);
30
}
31
return;
32
};
33

34
go(s, []);
35

36
return results;
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0