目录
代码效果
思路
- 先根据是否包含三个 '.' 符和七个 ':' 符初步筛选符合要求的IPv4和IPv6地址
- 将IP地址字符串按照分割符进行分割
- 分别判断每段分割数据是否符合要求
class Solution {
public:
//判断IPv4各段数据是否正确
bool validateInt(string s){
int len=s.length();
int i;
int num;
if(s=="") //判断是否为空
return false;
if(len!=1&&s[0]=='0') //判断是否包含前导0,例如 "001"
return false;
for(i=0;i<len;i++){ //判断是否包含非法字符
if(s[i]<'0'||s[i]>'9')
return false;
}
num=atoi(s.c_str()); //string类型转为int类型
if(num<0||num>255) //判断是否在[0,255]内
return false;
return true;
}
//判断IPv6各段数据是否正确
bool validateIPv6(string s){
int len=s.length();
int i;
int num;
if(len==0||len>4) //判断IPv6各段长度是否在[1,4]内
return false;
for(i=0;i<len;i++){ //判断是否包含非法字符
if(s[i]>='0'&&s[i]<='9'||s[i]>='a'&&s[i]<='f'||s[i]>='A'&&s[i]<='F')
continue;
else
return false;
}
return true;
}
string validIPAddress(string queryIP) {
vector<string> s;
int i=0;
if(count(queryIP.begin(),queryIP.end(),'.')==3){ //queryIP中包含三个'.',IPv4地址的第一步筛选
//以'.'为界分割字符串,分割出来的子串存在 vector<string>中
int pos=0;
int end=queryIP.find('.');
while(end!=-1){
s.push_back(queryIP.substr(pos,end-pos));
pos=end+1;
end=queryIP.find('.',pos);
}
s.push_back(queryIP.substr(pos,queryIP.length()-pos));
//判断各数据段是否符合要求
for(i=0;i<4;i++){
if(!validateIPv4(s[i]))
return "Neither";
}
return "IPv4";
}else if(count(queryIP.begin(),queryIP.end(),':')==7){ //queryIP是否包含7个':'
//以':'为界分割字符串,分割出来的子串存在 vector<string>中
int pos=0;
int end=queryIP.find(':');
while(end!=-1){
s.push_back(queryIP.substr(pos,end-pos));
pos=end+1;
end=queryIP.find(':',pos);
}
s.push_back(queryIP.substr(pos,queryIP.length()-pos));
//判断各数据段是否符合要求
for(i=0;i<8;i++){
if(!validateIPv6(s[i]))
return "Neither";
}
return "IPv6";
}else {
return "Neither";
}
}
};