题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
class Solution { public: /** * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ vector<string> split(string& s, char c) { vector<string> ret; for (int i = 0; i < s.size(); i++) { int j = i; while (j < s.size() && s[j] != c) j++; ret.push_back(s.substr(i, j - i)); i = j; } return ret; } string check_ipv4(string& ip) { auto items = split(ip, '.'); if (items.size() != 4) return "Neither"; for (auto& item : items) { if (item.size() && item[0] == '0') return "Neither"; for (auto& c : item) { if (c < '0' || c > '9') return "Neither"; } int t = stoi(item); if (t < 0 || t > 255) return "Neither"; } return "IPv4"; } bool check(char c) { if (isdigit(c)) return true; if (c >= 'a' && c <= 'f') return true; if (c >= 'A' && c <= 'F') return true; return false; } string check_ipv6(string& ip) { auto items = split(ip, ':'); if (items.size() != 8) return "Neither"; for (auto& item : items) { if (item.empty() || item.size() > 4) return "Neither"; for (auto& c : item) { if (!check(c)) return "Neither"; } } return "IPv6"; } string solve(string IP) { // write code here if (IP[IP.size() - 1] == ':') return "Neither"; if (IP.find('.') == -1 && IP.find(':') == -1) return "Neither"; if (IP.find('.') != -1) return check_ipv4(IP); if (IP.find(':') != -1) return check_ipv6(IP); return "Neither"; } };
- 思路:面向测试样例编程
- 1、根据' . '和' : '判断是ipv4还是ipv6
- 2、按照分隔符划分每一部分
- 3、ipv4特性:4个数字,数字范围在0~255,没有前导0
- 4、ipv6特性:8个16进制数(0~9,a~f,A~F)
- 时间复杂度:O(n)
- 空间复杂度:O(1)