[LeetCode] Restore IP Addresses

93. Restore IP Addresses

Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order.

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. For example, “0.1.2.201” and “192.168.1.1” are valid IP addresses and “0.011.255.245”, “192.168.1.312” and “192.168@1.1” are invalid IP addresses.

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
class Solution {
long _validStoi(string s) {
return s[0] == '0' ? s == "0" ? 0 : 256 : s.length() > 3 ? 256 : stoi(s);
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
string ip1, ip2, ip3, ip4;
for(int i1 = 0; i1 < s.length(); i1++) {
ip1 += s[i1]; ip2 = "";
if(_validStoi(ip1) > 255) break;
for(int i2 = i1 + 1; i2 < s.length(); i2++) {
ip2 += s[i2]; ip3 = "";
if(_validStoi(ip2) > 255) break;
for(int i3 = i2 + 1; i3 < s.length() - 1; i3++) {
ip3 += s[i3]; ip4 = s.substr(i3 + 1);
if(_validStoi(ip3) > 255) break;
if(_validStoi(ip4) > 255) continue;
res.push_back(ip1 + "." + ip2 + "." + ip3 + "." + ip4);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/26/PS/LeetCode/restore-ip-addresses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.