-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_213.js
More file actions
33 lines (27 loc) Β· 743 Bytes
/
problem_213.js
File metadata and controls
33 lines (27 loc) Β· 743 Bytes
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
/**
* Finds all combinations of IP addresses
* @param {string} s
* @return {string[]}
*/
function formatIPAddresses(num) {
const result = [];
const acc = [];
const dfs = (arr, s) => {
const prev = arr[arr.length - 1];
if (prev > 255) return false;
if (arr.length < 4 && s === '') return false;
if (prev && prev.length > 1 && prev[0] === '0') return false;
if (arr.length === 3) {
if (s > 255 || (s.length > 1 && s[0] === '0')) return false;
result.push([...arr, s].join('.'));
return true;
}
for (let i = 1; i < 4; i++) {
dfs([...arr, s.slice(0, i)], s.slice(i));
}
return true;
};
dfs(acc, num);
return result;
}
console.log(formatIPAddresses('2542540123'));