Skip to content

Commit 4432d1c

Browse files
Create restore_ip_addresses.cpp
1 parent 6d8b040 commit 4432d1c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

restore_ip_addresses.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//slow approach. I believe its related with concatenation on the fly. +=
2+
class Solution {
3+
void getIPAddresses(vector<string> &temp, vector<string> &IPs, string &s, int index) {
4+
if(index == s.length() && temp.size() == 4) {
5+
string validIP = temp[0] + '.' + temp[1] + '.' + temp[2] + '.' + temp[3] ;
6+
IPs.push_back(validIP);
7+
return;
8+
}
9+
10+
string tempStr = "";
11+
for(int i = index ; i< s.length() && temp.size() < 4; i++) {
12+
if(s[i] - '0' > 9) {
13+
continue;
14+
}
15+
tempStr += s[i];
16+
int tempInt = stoi(tempStr);
17+
if(0 <= tempInt && tempInt <= 255) {
18+
temp.push_back(tempStr);
19+
getIPAddresses(temp, IPs, s, i+1);
20+
temp.pop_back();
21+
}
22+
if(tempInt <= 0 || tempInt > 255) {
23+
break;
24+
}
25+
}
26+
}
27+
28+
public:
29+
vector<string> restoreIpAddresses(string s) {
30+
vector<string> IPs;
31+
vector<string> temp;
32+
getIPAddresses(temp, IPs, s, 0);
33+
return IPs;
34+
}
35+
36+
37+
};

0 commit comments

Comments
 (0)