forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0468.cpp
More file actions
executable file
·64 lines (57 loc) · 1.35 KB
/
LC0468.cpp
File metadata and controls
executable file
·64 lines (57 loc) · 1.35 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
/*
Problem Statement: https://leetcode.com/problems/validate-ip-address/
*/
class Solution {
public:
string validIPAddress(string IP) {
string token;
vector<string> g4, g8;
istringstream ss(IP);
// split by '.' for IPv4
while (getline(ss, token, '.'))
g4.push_back(token);
if (!IP.empty() && IP.back() == '.')
g4.push_back(string());
// reset stringstream
ss.clear();
ss.str(IP);
// split by ':' for IPv6
while (getline(ss, token, ':'))
g8.push_back(token);
if (!IP.empty() && IP.back() == ':')
g8.push_back(string());
// call matching function
if (g4.size() == 4)
return ipv4(g4);
else if (g8.size() == 8)
return ipv6(g8);
else
return "Neither";
}
string ipv4(vector<string>& groups) {
bool valid = true;
for (string g: groups) {
valid &= (g.length() && g.length() <= 3);
valid &= std::all_of(g.begin(), g.end(), ::isdigit);
if (g.length() > 1)
valid &= g[0] != '0';
if (valid)
valid &= stoi(g) < 256;
if (!valid)
return "Neither";
}
return "IPv4";
}
string ipv6(vector<string>& groups) {
bool valid = true;
for (string& g: groups) {
valid &= (g.length() && g.length() <= 4);
valid &= all_of(g.begin(), g.end(), [](char& c) {
return ::isdigit(c) || (tolower(c) >= 'a' && tolower(c) <= 'f');
});
if (!valid)
return "Neither";
}
return "IPv6";
}
};