题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#include <cstdlib> #include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ vector<string> Split(string IP) { vector<string> temp; string block = ""; for(int i = 0;i<IP.size();i++) { if(IP[i] != '.' && IP[i] != ':') { block += IP[i]; if(i == IP.size() - 1) { temp.push_back(block); break; } } else { temp.push_back(block); block = ""; if(i == IP.size()-1) temp.push_back(block);//这一行写的很差,为了过测试点的 } } return temp; } bool isIPv4(string IP) { int index = IP.find('.'); if(index != string::npos) return true; else return false; } bool checkIPv4(string str) { if(str.size() > 3) return false; if(str == "") return false; for(int i = 0;i<str.size();i++) { if(str[i] < '0' || str[i] > '9') return false; } int value = atoi(str.c_str()); if(value > 255) return false; char first = str[0]; if(first == '0' && str.size() != 1) return false; return true; } bool checkIPv6(string str) { if (str.size() > 4 || str.size() == 0) { return false; } for (int i = 0; i < str.size(); i++) { if (!(isdigit(str[i]) || (str[i] >= 'a' && str[i] <= 'f') || (str[i] >= 'A' && str[i] <= 'F'))) { return false; } } return true; } string solve(string IP) { // write code here vector<string> ss; ss = Split(IP); if(isIPv4(IP)) { if(ss.size() != 4) return "Neither"; for(int i = 0;i<ss.size();i++) { if(!checkIPv4(ss[i])) return "Neither"; } return "IPv4"; } else { if(ss.size() != 8) return "Neither"; for(int i = 0;i<ss.size();i++) { if(!checkIPv6(ss[i])) return "Neither"; } return "IPv6"; } } };