-
Notifications
You must be signed in to change notification settings - Fork 20
/
RestoreIPAddresses.js
76 lines (66 loc) · 1.96 KB
/
RestoreIPAddresses.js
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
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Given a string containing only digits, restore it by returning all possible valid IP address combinations.
*
* For example:
* Given "25525511135",
*
* return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*
* Accepted.
*/
/**
* @param {string} s
* @return {string[]}
*/
let restoreIpAddresses = function (s) {
let results = [];
if (s === null || s.length < 4 || s.length > 12) {
return results
}
for (let i = 1; i < 4; i++) {
for (let j = 1; j < 4; j++) {
for (let k = 1; k < 4; k++) {
for (let m = 1; m < 4; m++) {
if (i + j + k + m === s.length) {
let a = parseInt(s.substring(0, i));
let b = parseInt(s.substring(i, j + i));
let c = parseInt(s.substring(i + j, k + i + j));
let d = parseInt(s.substring(i + j + k, m + i + j + k));
if (a <= 255 && b <= 255 && c <= 255 && d <= 255) {
let str = a.toString() + "." + b + "." + c + "." + d;
if (str.length === s.length + 3) {
results.push(str);
}
}
}
}
}
}
}
return results
};
if (restoreIpAddresses("1").length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (restoreIpAddresses("111").length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (restoreIpAddresses("1111111111111").length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (restoreIpAddresses("1111").toString() === ["1.1.1.1"].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (restoreIpAddresses("25525511135").toString() === ["255.255.11.135", "255.255.111.35"].toString()) {
console.log("pass")
} else {
console.error("failed")
}