-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
31 lines (30 loc) · 929 Bytes
/
solution.ts
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
function restoreIpAddresses (s: string): string[] {
const result:string[] = [];
const backTracking = (segments:string[], start:number) => {
if (segments.length > 4) {
return;
}
if (start === s.length) {
if (segments.length === 4) {
result.push(segments.join('.'));
}
return;
}
if (s[start] === '0') {
segments.push('0');
backTracking(segments, start + 1);
segments.pop();
} else {
for (let end = start + 1; end <= Math.min(s.length, start + 3); end++) {
const addr = s.slice(start, end);
if (+addr < 256) {
segments.push(addr);
backTracking(segments, end);
segments.pop();
}
}
}
};
backTracking([], 0);
return result;
}