-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestore ip address
33 lines (29 loc) · 1.05 KB
/
restore ip address
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
class Solution {
vector<string> ans;
public:
void restoreDFS(string s, string temp, int dot, int index) {
if (index == s.size() and dot == 4) {
temp.pop_back();
ans.push_back(move(temp));
return;
}
if (index >= s.size() or dot >= 4) {
return;
}
// case 1: For first dot it doesnot matter what number it is
restoreDFS(s, temp + s[index] + '.', dot + 1, index + 1);
// case 2: For 2 numbers the first char cannot be a zero
if (s[index] != '0') {
restoreDFS(s, temp + s.substr(index, 2) + '.', dot + 1, index + 2);
}
// case 3: For 3 numbers whole number cannot be larger than 255 with no leading zero
if (s[index] != '0' and (stoi(s.substr(index, 3)) < 256)) {
restoreDFS(s, temp + s.substr(index, 3) + '.', dot + 1, index + 3);
}
}
vector<string> restoreIpAddresses(string s) {
if (s.size() > 12 or s.size() < 4) return ans;
restoreDFS(s, "", 0, 0);
return ans;
}
};