-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestoreIpAddresses.cpp
More file actions
executable file
·75 lines (71 loc) · 2.11 KB
/
RestoreIpAddresses.cpp
File metadata and controls
executable file
·75 lines (71 loc) · 2.11 KB
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
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void dfs(int segId, int segStart) {
if (segStart >= length) return;
// cout << segId << " " << segStart << endl;
if (segId == 3) {
if (str[segStart] == '0' && segStart != length - 1) return;
int lastByte = std::stoi(str.substr(segStart));
if (lastByte >= 0 && lastByte <= 255) {
string temp;
for (int e: segs) {
temp += to_string(e) + ".";
}
temp += to_string(lastByte);
addresses.push_back(temp);
// cout << "segs: ";
// for (int r: segs)
// cout << r << " ";
// cout << lastByte << endl;
}
return;
}
if (str[segStart] == '0') {
segs.push_back(0);
dfs(segId + 1, segStart + 1);
segs.pop_back();
}
else {
for (int i = 1; i <= 3; i++) {
if (segStart + i >= length) return;
int nextByte = std::stoi(str.substr(segStart, i));
// cout << "segs: ";
// for (int r: segs)
// cout << r << " ";
// cout << "nextByte: " << nextByte << endl;
if (nextByte >= 0 && nextByte <= 255) {
segs.push_back(nextByte);
dfs(segId + 1, segStart + i);
segs.pop_back();
}
}
}
}
vector<string> restoreIpAddresses(string s) {
addresses.clear();
segs.clear();
length = s.size();
if (length < 4 || length > 12) return addresses;
str = s;
dfs(0, 0);
return addresses;
}
private:
vector<string> addresses;
vector<int> segs;
string str;
int length;
};
int main() {
string str = "25525511135";
Solution s;
vector<string> re = s.restoreIpAddresses(str);
for (string r: re)
cout << r << " ";
cout << endl;
return 0;
}