模拟题
class Solution {
public:
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
string solve(string IP) {
// write code here
const string IPS[3] = {"IPv4", "IPv6", "Neither"};
int idx = 2;
vector<string> vec;
int n = IP.length();
string str;
char flag = '#';
for(int i = 0; i < n; i ++){
if(i > 0){
if(IP[i] == '.' || IP[i] == ':'){
if(IP[i - 1] == IP[i]) return IPS[2];
}
}
if(IP[i] == '.' || IP[i] == ':'){
vec.push_back(str);
str = "";
if(flag == '#') flag = IP[i];
else{
if(flag != IP[i]) return IPS[2];
}
}else str += IP[i];
}
vec.push_back(str);
if(flag == '.'){
if(vec.size() != 4 || !isIPv4(vec)) return IPS[2];
else return IPS[0];
}else{
if(vec.size() != 8 || !isIPv6(vec)) return IPS[2];
else return IPS[1];
}
return IPS[2];
}
bool isIPv4(const vector<string>& vec){
for(int i = 0; i < 4; i ++){
if(vec[i].length() > 1 && vec[i][0] == '0') return false;
if(stoi(vec[i]) >= 256) return false;
}
return true;
}
bool isIPv6(const vector<string>& vec){
unordered_set<char> ust;
for(char ch = '0'; ch <= '9'; ch ++) ust.insert(ch);
for(char ch = 'a'; ch <= 'f'; ch ++) ust.insert(ch);
for(char ch = 'A'; ch <= 'F'; ch ++) ust.insert(ch);
for(int i = 0; i < 8; i ++){
if(vec[i].length() > 4) return false;
for(int j = 0; j < vec[i].length(); j ++){
if(ust.count(vec[i][j]) == 0) return false;
}
}
return true;
}
}; 
京公网安备 11010502036488号