class Solution {
public:
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
// 首先编写split函数
// 然后将IP地址经过split函数变换为string数组
// 随后考虑边界条件:数组长度,每个数组的元素个数,以及开头元素等
vector<string> split(string s, char op) {
s += op;
vector<string> res;
for(int i = 0; i < s.size(); i++) {
string str = "";
while(s[i] != op) {
str += s[i++];
}
res.push_back(str);
}
return res;
}
bool ifIPv4(vector<string> arr) {
if(arr.size() != 4)
return false;
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
int num = stoi(arr[i]);
if(num < 0 || num > 255)
return false;
if(arr[i][0] == '0' && arr[i].size() > 1)
return false;
if(arr[i][j] < '0' || arr[i][j] > '9')
return false;
}
}
return true;
}
bool ifIPv6(vector<string> arr) {
if(arr.size() != 8)
return false;
for(int i = 0; i < arr.size(); i++) {
if(arr[i].size() > 4)
return false;
for(int j = 0; j < arr[i].size(); j++) {
if(arr[i][j] >= '0' && arr[i][j] <= '9' ||
arr[i][j] >= 'a' && arr[i][j] <= 'f' ||
arr[i][j] >= 'A' && arr[i][j] <= 'F')
continue;
else
return false;
}
}
return true;
}
string solve(string IP) {
// write code here
vector<string> arr4;
vector<string> arr6;
arr4 = split(IP, '.');
arr6 = split(IP, ':');
if(ifIPv4(arr4))
return "IPv4";
if(ifIPv6(arr6))
return "IPv6";
return "Neither";
}
};