-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestoreIPAddresses.cpp
More file actions
46 lines (42 loc) · 1.09 KB
/
RestoreIPAddresses.cpp
File metadata and controls
46 lines (42 loc) · 1.09 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
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
string cur;
vector<string> res;
if (s.size() < 4)
return res;
BackTracking(s, 0, 1, cur, res);
return res;
}
void BackTracking(string s, int idx, int place, string cur, vector<string>& res)
{
if (place > 4)
{
if (idx >= s.length())
{
cur.pop_back();
res.push_back(cur);
}
return;
}
else if (idx >= s.length())
{
return;
}
for (int i = 1; i <= 3; i++)
{
if (idx + i - 1 >= s.size())
break;
string sub = s.substr(idx, i);
if (sub.size() > 1 && sub[0] == '0')
break;
if (sub.length() < 3 || sub < "256")
{
cur.append(sub);
cur.append(1, '.');
BackTracking(s, idx + i, place + 1, cur, res);
cur.erase(cur.end() - i - 1, cur.end());
}
}
}
};