-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0093_restoreIpAddresses.cc
65 lines (61 loc) · 1.14 KB
/
Problem_0093_restoreIpAddresses.cc
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
private:
const int SEG_COUNT = 4;
vector<int> segments;
vector<string> ans;
public:
void process(string &s, int segId, int index)
{
if (segId == SEG_COUNT)
{
if (index == s.length())
{
string ipAddr;
for (int i = 0; i < SEG_COUNT; i++)
{
ipAddr += std::to_string(segments[i]);
if (i != SEG_COUNT - 1)
{
ipAddr += ".";
}
}
ans.push_back(std::move(ipAddr));
}
return;
}
if (index == s.length())
{
return;
}
if (s[index] == '0')
{
segments[segId] = 0;
process(s, segId + 1, index + 1);
return;
}
int num = 0;
for (int i = index; i < s.length(); i++)
{
num = num * 10 + (s[i] - '0');
if (num > 0 && num <= 0xff)
{
segments[segId] = num;
process(s, segId + 1, i + 1);
}
else
{
break;
}
}
}
vector<string> restoreIpAddresses(string s)
{
segments.resize(SEG_COUNT);
process(s, 0, 0);
return ans;
}
};