-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path93. Restore IP Addresses.c
92 lines (81 loc) · 2.07 KB
/
93. Restore IP Addresses.c
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
93. Restore IP Addresses
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)
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void gen_ip(const char *s, char *buff, int *seglen) {
int i, j, k;
for (i = 0; i < 4; i ++) {
strncpy(buff, s, seglen[i]);
s += seglen[i];
buff += seglen[i];
*buff = '.';
buff ++;
}
buff --;
*buff = 0;
}
int validate(const char *s, int len) {
int k = 0;
if (len > 1 && *s == '0') return 0;
while (len -- > 0) {
k = k * 10 + *s - '0';
s ++;
}
return k > 255 ? 0 : 1;
}
void bt(const char *s, char ***p, int *psz, int *pn, int total, int usedlen, int *seglen, int d) {
int i, k;
char buff[16];
if (d == 4) {
if (usedlen != total) return;
gen_ip(s, buff, seglen);
if (*psz == *pn) {
*psz *= 2;
*p = realloc(*p, *psz * sizeof(char *));
//assert(*p);
}
(*p)[*pn] = malloc((total + 4) * sizeof(char));
//assert((*p)[*pn]);
strcpy((*p)[*pn], buff);
(*pn) ++;
return;
}
for (i = 1; i <= 3; i ++) {
if (validate(&s[usedlen], i)) {
seglen[d] = i;
bt(s, p, psz, pn, total, usedlen + i, seglen, d + 1);
}
}
}
char** restoreIpAddresses(char* s, int* returnSize) {
char **p;
int psz, pn;
int seglen[4] = { 0 };
pn = 0;
psz = 10;
p = malloc(psz * sizeof(char *));
//assert(p);
bt(s, &p, &psz, &pn, strlen(s), 0, seglen, 0);
*returnSize = pn;
return p;
}
/*
Difficulty:Medium
Total Accepted:87.7K
Total Submissions:321.1K
Related Topics Backtracking String
*/