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