forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate IP Address.cpp
98 lines (97 loc) · 2.53 KB
/
Validate IP Address.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Solution {
public:
bool checkforIPv6(string IP){
int n = IP.size();
vector<string>store;
string s = "";
for(int i=0; i<n; i++){
if(IP[i] == ':'){
store.push_back(s);
s = "";
}
else{
s+=IP[i];
}
}
store.push_back(s);
if(store.size() != 8){
return false;
}
for(int i=0; i<store.size(); i++){
string s = store[i];
if(s.size() > 4 or s.size() == 0){
return false;
}
for(int j=0; j<s.size(); j++){
if(s[j] >= 'a' and s[j] <= 'f'){
continue;
}
else if(s[j] >= 'A' and s[j] <= 'F'){
continue;
}
else if(s[j] >= '0' and s[j] <= '9'){
continue;
}
else{
return false;
}
}
}
return true;
}
bool checkforIPv4(string IP){
int n = IP.size();
vector<string>store;
string s = "";
for(int i=0; i<n; i++){
if(IP[i] == '.'){
store.push_back(s);
s = "";
}
else{
s+=IP[i];
}
}
store.push_back(s);
if(store.size() != 4){
return false;
}
for(int i=0; i<store.size(); i++){
string s = store[i];
if(s.size() > 3 or s.size() == 0){
return false;
}
int num = 0;
for(int j=0; j<s.size(); j++){
if(s.size() >= 2 and s[0] == '0' and s[1] == '0'){
return false;
}
if(s.size() >= 2 and s[0] == '0' and s[1] != '0'){
return false;
}
if(s[j] >= '0' and s[j] <= '9'){
// Do nothing.
}
else{
return false;
}
num = num*10 + (s[j]-'0');
}
if(num > 255 or num < 0){
return false;
}
}
return true;
}
string validIPAddress(string queryIP) {
bool IPv6 = checkforIPv6(queryIP);
bool IPv4 = checkforIPv4(queryIP);
if(IPv6){
return "IPv6";
}
if(IPv4){
return "IPv4";
}
return "Neither";
}
};