-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestore IP Addresses
30 lines (28 loc) · 962 Bytes
/
Restore IP Addresses
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
class Solution {
public:
bool valid(string s){
if (s.size()==3 && (atoi(s.c_str())>255 || atoi(s.c_str())==0)){return false;}
if (s.size()==3 && s[0]=='0'){return false;}
if (s.size()==2 && atoi(s.c_str())==0){return false;}
if (s.size()==2 && s[0]=='0'){return false;}
return true;
}
void getRes(string s, string r, vector<string> &res, int k){
if (k==0){
if (s.empty()){res.push_back(r);}
return;
}else{
for (int i=1;i<=3;i++){ //number of digits between "."
if (s.size()>=i && valid(s.substr(0,i))){
if (k==1){getRes(s.substr(i),r+s.substr(0,i),res,k-1);}
else{getRes(s.substr(i),r+s.substr(0,i)+".",res,k-1);}
}
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> res;
getRes(s,"",res,4);
return res;
}
};