Skip to content

Commit 0546807

Browse files
author
ZQKC
committed
93.Restore IP Addresses
1 parent e86d895 commit 0546807

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

93.Restore IP Addresses.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
private:
3+
void dfs(const std::string &s, int beg, std::string ip, int num, std::vector<std::string> &ans) {
4+
if (beg == s.length() && num == 4) {
5+
ans.push_back(ip);
6+
}
7+
if (s.length() - beg > (4 - num) * 3) {
8+
return ;
9+
}
10+
11+
std::string tmp_ip;
12+
for (int i = 0, val = 0; i < 3; ++i) {
13+
val *= 10;
14+
val += (s[beg + i] - '0');
15+
tmp_ip += s[beg + i];
16+
if (val > 255 || (val != 0 && tmp_ip[0] == '0') || (val == 0 && tmp_ip.length() > 1)) {
17+
continue;
18+
}
19+
if (num == 0)
20+
dfs(s, beg + i + 1, tmp_ip, num + 1, ans);
21+
else
22+
dfs(s, beg + i + 1, ip + '.' + tmp_ip, num + 1, ans);
23+
}
24+
}
25+
26+
public:
27+
vector<string> restoreIpAddresses(string s) {
28+
std::vector<std::string> ans;
29+
dfs(s, 0, "", 0, ans);
30+
return ans;
31+
}
32+
};

0 commit comments

Comments
 (0)