题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#include <sstream> #include <string> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ bool isIPV4(string IP){ // 判断是否为IPV4 stringstream ss(IP); vector<string> vec; string s; while(getline(ss, s, '.')){ // 按照 '.'分割地址 vec.push_back(s); } if(vec.size() !=4) return false; // 若不为4段则直接返回错误 for(auto str: vec){ if(stoi(str) > 255 ) return false; // 不能大于255 if(str[0] == '0') return false; // 开头不能为0 for(char c : str){ if(c>='0' && c<='9'){ continue; }else return false; } } return true; } bool isIPV6(string IP){ // 判断是否IPV6 stringstream ss(IP); vector<string> vec; string s; while(getline(ss, s, ':')){ // 分割地址 if(s == "") return false; vec.push_back(s); } int dotCount = 0; //判断 ':'个数 for(char c : IP){ if(c == ':')dotCount++; } if(dotCount != 7) return false; if(vec.size() != 8) return false; for(auto str : vec){ if(str.size()>4) return false; // 每段不能超过四位 //if(str.size() == 1 && str[0] == '0') return false; for(int i = 0; i<str.size(); i++){ // 判断符号是否正确 if( str[i] >= '0' && str[i] <='9' ){ continue; }else if(str[i] >='a' && str[i]<='f' ){ continue; }else if(str[i] >='A' && str[i]<='F' ){ continue; }else{ return false; } } } return true; } string solve(string IP) { // write code here if(isIPV4(IP)) return "IPv4"; if(isIPV6(IP)) return "IPv6"; return "Neither"; } };