-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrestore_ip_addresses.cpp
37 lines (33 loc) · 1.09 KB
/
restore_ip_addresses.cpp
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
//slow approach. I believe its related with concatenation on the fly. +=
class Solution {
void getIPAddresses(vector<string> &temp, vector<string> &IPs, string &s, int index) {
if(index == s.length() && temp.size() == 4) {
string validIP = temp[0] + '.' + temp[1] + '.' + temp[2] + '.' + temp[3] ;
IPs.push_back(validIP);
return;
}
string tempStr = "";
for(int i = index ; i< s.length() && temp.size() < 4; i++) {
if(s[i] - '0' > 9) {
continue;
}
tempStr += s[i];
int tempInt = stoi(tempStr);
if(0 <= tempInt && tempInt <= 255) {
temp.push_back(tempStr);
getIPAddresses(temp, IPs, s, i+1);
temp.pop_back();
}
if(tempInt <= 0 || tempInt > 255) {
break;
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> IPs;
vector<string> temp;
getIPAddresses(temp, IPs, s, 0);
return IPs;
}
};