0468.cpp (1285B)
1 class Solution { 2 static string valid4(const string &s) { 3 stringstream ss(s); 4 string crnt; 5 int cnt = 0; 6 7 while (getline(ss, crnt, '.')) { 8 if (size(crnt) == 0 || size(crnt) > 3) break; 9 if (any_of(begin(crnt), end(crnt), [](char c) { return isalpha(c); })) break; 10 if (size(crnt) > 1 && crnt[0] == '0') break; 11 if (stoi(crnt) >= 256) break; 12 cnt++; 13 } 14 15 return cnt == 4 ? "IPv4" : "Neither"; 16 } 17 18 static string valid6(const string &s) { 19 stringstream ss(s); 20 string crnt; 21 int cnt = 0; 22 23 while (getline(ss, crnt, ':')) { 24 if (size(crnt) == 0 || size(crnt) > 4) break; 25 cnt++; 26 } 27 28 return cnt == 8 ? "IPv6" : "Neither"; 29 } 30 31 public: 32 string validIPAddress(const string &queryIP) const { 33 int dot = 0, col = 0; 34 35 for (const char c : queryIP) { 36 if (c == '.') 37 dot++; 38 else if (c == ':') 39 col++; 40 else if (!isxdigit(c)) 41 return "Neither"; 42 } 43 44 if (dot && col) return "Neither"; 45 if (dot ? dot != 3 : col != 7) return "Neither"; 46 47 return dot ? valid4(queryIP) : valid6(queryIP); 48 } 49 };