#include <cctype> class Solution { public: /** * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ bool isIPV4(string IP) { int n = IP.size(); if(n == 0) return false; int spotcount = 0; int num = 0; if(IP[0] == '.') return false; for(int i = 0;i<n;++i) { if(i>0 && IP[i] == '.' && IP[i-1] == '.') return false; if(isalpha(IP[i]) || IP[i] == ':') return false; if(isalnum(IP[i])) { num = num * 10 + IP[i] - '0'; if(num == 0) return false; } if(IP[i] == '.') { spotcount++; if(num <= 0 || num > 255) return false; num = 0; } } if(spotcount == 3) return true; else return false; } bool isIPV6(string IP) { int n = IP.size(); if(n == 0) return false; int spotcount = 0; int size = 0; for(int i = 0;i<n;++i) { if(i>0 && IP[i] == ':' && IP[i-1] == ':') return false; if(isalpha(IP[i])) { if((IP[i] >= 'g' && IP[i] <= 'z') || (IP[i] >= 'G' && IP[i] <= 'Z')) return false; } if(IP[i] != ':') { size++; } else { if(size > 4) return false; size = 0; spotcount++; } } if(spotcount == 7) return true; else return false; } string solve(string IP) { // write code here if(isIPV4(IP)) return "IPv4"; else if(isIPV6(IP)) return "IPv6"; else return "Neither"; } };
解题思路:模拟