题解 | 验证IP地址
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ bool isV4(string& s) { for (char c : s) { if (c == '.') return true; else if (c == ':') return false; } return false; } bool val_V4(string& s) { s.push_back('.'); int num = 0; int val_cnt = 0; for (char c : s) { if (c == '.') { if (num > 255 || num < 0) return false; num = 0; val_cnt++; } else if (c > '9' || c < '0') return false; else { if (num == 0 && c == '0') return false; num = num * 10 + (c - '0'); } } if (val_cnt != 4) return false; return true; } bool val_V6(string& s) { s.push_back(':'); int cnt = 0; int val_cnt = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] == ':') { if (cnt == 4) { val_cnt++; cnt = 0; } else if (cnt == 1) { if (i > 0 && s[i-1] == '0') { val_cnt++; cnt = 0; } } else return false; } else { if (!((s[i] <= '9' && s[i] >= '0') || (s[i] >= 'a' && s[i] <= 'f') || (s[i] >= 'A' && s[i] <= 'F'))) return false; else cnt++; } } if (val_cnt == 8) return true; return false; } string solve(string IP) { if (isV4(IP)) { if (val_V4(IP)) return "IPv4"; } else { if (val_V6(IP)) return "IPv6"; } return "Neither"; } };