题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
class Solution { public: bool validIPv4(string& s, int be, int en) { //判断一个组是否符合IPv4 if (en - be > 3 || en <= be) return false; //长度限制 if (s[be] == '0' && en - be > 1) { //不能0开头 return false; } int num = 0; //大小限制 for (int i = be; i < en; i++) { if (s[i] >= '0' && s[i] <= '9') { num = num * 10 + s[i] - '0'; } else return false; } return num < 256; } bool validIPv6(string& s, int be, int en) { if (en - be > 4 || en <= be) return false; if (s[be] == '0' && s[be + 1] == '0') { return false; } for (int i = be; i < en; i++) { if ((s[i] < '0' || s[i] > '9') && (s[i] < 'a' || s[i] > 'f') && (s[i] < 'A' || s[i] > 'F')) { return false; } } return true; } bool isIPv4(string& IP) { //判断是否符合IPv4 if (IP.size() < 7 || IP.size() > 15) return false; //长度限制 int count = 0; //组数限制 for (int i = 0, j = 0; i <= IP.size(); j++) { if (IP[j] == '.' || IP[j] == '\0') { if (!validIPv4(IP, i, j)) return false; i = j + 1; count++; } } return count == 4; } bool isIPv6(string& IP) { if (IP.size() < 15 || IP.size() > 39) return false; int count = 0; for (int i = 0, j = 0; i <= IP.size(); j++) { if (IP[j] == ':' || IP[j] == '\0') { if (!validIPv6(IP, i, j)) return false; i = j + 1; count++; } } return count == 8; } string solve(string IP) { if (isIPv4(IP)) return "IPv4"; else if (isIPv6(IP)) return "IPv6"; else return "Neither"; } };