forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
37 lines (32 loc) · 924 Bytes
/
solution.h
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
#include <vector>
using std::vector;
#include <string>
using std::string;
class Solution {
vector<string> ret;
bool valid(const string &s) {
if (s.size() > 1 && s[0] == '0') return false;
int num = std::stoi(s);
return 0 <= num && num <= 255;
}
void restore(const string &origin, const string &ip, int part)
{
if (part == 0) {
if (origin.empty()) ret.push_back(ip);
return;
}
for (size_t i=1; i<4; ++i) {
if (origin.size() < i) break;
string section = origin.substr(0, i);
if (valid(section)) {
if (part != 1) section.append(".");
restore(origin.substr(i), ip+section, part-1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
if (s.size() >= 4 && s.size() <= 12) restore(s, "", 4);
return ret;
}
};