题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
#include<sstream>
#include<vector>
#include<string>
string ipv4Validation(vector<string> vecStr){
int addNum = vecStr.size();
if(addNum!=4){
return "Neither";
}
for(string str:vecStr){
if(str==""){return "Neither";}
if(str[0]=='0'){return "Neither";}
for(char ch : str){
if(ch>='0'&&ch<='9'){continue;}
else{return "Neither";}
}
int num = stoi(str);
if(num>255){return "Neither";}
}
return "IPv4";
}
string ipv6Validation(vector<string> vecStr){
int addNum = vecStr.size();
if(addNum!=8){
return "Neither";
}
for(string str:vecStr){
if(str==""){return "Neither";}
if(str.length()>4){return "Neither";}
for(int i=0;i<str.length();i++){
char ch = str[i];
if(ch>='0'&&ch<='9'){continue;}
else if(ch>='a'&&ch<='f'){continue;}
else if(ch>='A'&&ch<='F'){continue;}
else{return "Neither"; }
}
}
return "IPv6";
}
string solve(string IP) {
// write code here
if(IP[IP.length()-1]=='.'||IP[IP.length()-1]==':'){return "Neither";}
stringstream ssInput(IP);
vector<string> vecStr;
string instr;
while(getline(ssInput,instr,'.')){
vecStr.push_back(instr);
}
if(vecStr.size()==1){
vecStr.clear();
stringstream ssInput2(IP);
while(getline(ssInput2,instr,':')){
vecStr.push_back(instr);
}
return ipv6Validation(vecStr);
}
else{
return ipv4Validation(vecStr);
}
}
};
查看23道真题和解析