Skip to content

Commit 2629f23

Browse files
restore-ip-addresses (ignacio-chiazzo#22)
1 parent 5eb29ff commit 2629f23

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
https://leetcode.com/problems/restore-ip-addresses/description/
3+
4+
93. Restore IP Addresses
5+
6+
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
7+
8+
Example:
9+
10+
Input: "25525511135"
11+
Output: ["255.255.11.135", "255.255.111.35"]
12+
*/
13+
14+
var restoreIpAddresses = function(s) {
15+
var restore = restoreInputBits("", s, 4);
16+
17+
var ret = [];
18+
for(var i = 0; i < restore.length; i++) {
19+
ret.push(restore[i].join("."));
20+
}
21+
22+
return ret;
23+
};
24+
25+
var restoreInputBits = function(partial, s, num) {
26+
if(s.length == 0 && num == 0 )
27+
return [partial];
28+
if(s.length < num || s.length > num * 3 || num == 0)
29+
return [];
30+
31+
const oneNum = restoreInputBits([...partial, s.slice(0, 1)], s.slice(1), num - 1);
32+
33+
if(s.length === 1 || s.slice(0, 1) === "0") {
34+
return oneNum
35+
};
36+
37+
const twoNums = restoreInputBits([...partial, s.slice(0, 2)], s.slice(2), num - 1);
38+
39+
if(s.length === 2 || s.slice(0, 3) > 255) {
40+
return [...oneNum, ...twoNums]
41+
};
42+
43+
const threeNums = restoreInputBits([...partial, s.slice(0, 3)], s.slice(3), num - 1);
44+
45+
return [...oneNum, ...twoNums, ...threeNums];
46+
}
47+
48+
var main = function() {
49+
console.log(restoreIpAddresses("010010"));
50+
console.log(restoreIpAddresses("25525511135"));
51+
}
52+
53+
main();
54+
55+
module.exports.main = main

0 commit comments

Comments
 (0)