leetcode - 468. 验证IP地址
题目
代码
#include <iostream>
#include <vector>
using namespace std;
string isIPv4(string queryIP){
int n = queryIP.size();
int tn = 0;
int flag = 0;
int num = 0;
int count = 0;
for(int i = 0; i < n; i++){
if(queryIP[i] == '.'){
if(flag == 0 || tn < 0 || tn > 255){
return "Neither";
}
num++;
tn = 0; flag = 0; count = 0;
}else if('0' <= queryIP[i] && queryIP[i] <= '9'){
if(flag == 0){
if(i+1 < n && queryIP[i] == '0' && queryIP[i+1] != '.'){
return "Neither";
}
flag = 1;
}
count++;
if(count > 3){
return "Neither";
}
tn = tn * 10 + queryIP[i] - '0';
}else{
return "Neither";
}
}
if(flag == 0 || tn < 0 || tn > 255 || num != 3){
return "Neither";
}
return "IPv4";
}
string isIPv6(string queryIP){
int n = queryIP.size();
int count = 0;
int num = 0;
for(int i = 0; i < n; i++){
if(queryIP[i] == ':'){
if(count < 1 || count > 4){
return "Neither";
}
num++;
count = 0;
}else if(('0' <= queryIP[i] && queryIP[i] <= '9')
|| ('A' <= queryIP[i] && queryIP[i] <= 'F')
|| ('a' <= queryIP[i] && queryIP[i] <= 'f')){
count++;
}else{
return "Neither";
}
}
if(count < 1 || count > 4 || num != 7){
return "Neither";
}
return "IPv6";
}
string validIPAddress(string queryIP) {
int n = queryIP.size();
int flag = 0;
string res;
for(int i = 0; i < n; i++){
if(queryIP[i] == '.'){
flag = 1;
break;
}else if(queryIP[i] == ':'){
flag = 2;
break;
}
}
if(flag == 1){
res = isIPv4(queryIP);
}else if(flag == 2){
res = isIPv6(queryIP);
}else if(flag == 0){
res = "Neither";
}
return res;
}
int main(){
string queryIP, res;
cin>>queryIP;
res = validIPAddress(queryIP);
cout<<res;
return 0;
}
|