Skip to content

Commit 32d9ab0

Browse files
authored
Update 93-restore-ip-addresses.js
1 parent b44cda5 commit 32d9ab0

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

93-restore-ip-addresses.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,35 @@ const restoreIpAddresses = function(s) {
2727
}
2828
}
2929
}
30-
3130
return res;
3231
};
32+
33+
// another method
34+
35+
/**
36+
* @param {string} s
37+
* @return {string[]}
38+
*/
39+
const restoreIpAddresses = function(s) {
40+
const ans = [];
41+
const stack = [];
42+
let ipstr;
43+
const len = s.length;
44+
function restoreIp(start) {
45+
if (stack.length > 4) return;
46+
if (stack.length === 4 && start > len - 1) {
47+
ans.push(stack.slice().join("."));
48+
return;
49+
}
50+
for (let i = start; i < start + 3; i++) {
51+
if (i > len - 1) return;
52+
ipstr = s.substring(start, i + 1);
53+
if ((ipstr[0] === "0" && ipstr.length !== 1) || ipstr > 255) return;
54+
stack.push(ipstr);
55+
restoreIp(i + 1);
56+
stack.pop();
57+
}
58+
}
59+
restoreIp(0);
60+
return ans;
61+
};

0 commit comments

Comments
 (0)