- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of C++ from the credited upstream file 468.cpp.
- The implementation keeps its working state in language-native values and containers.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string validIPAddress(string queryIP) {4 string digit;5 istringstream iss(queryIP);6 7 if (ranges::count(queryIP, '.') == 3) {8 for (int i = 0; i < 4; ++i) 9 if (!getline(iss, digit, '.') || !isIPv4(digit))10 return "Neither";11 return "IPv4";12 }13 14 if (ranges::count(queryIP, ':') == 7) {15 for (int i = 0; i < 8; ++i) 16 if (!getline(iss, digit, ':') || !isIPv6(digit))17 return "Neither";18 return "IPv6";19 }20 21 return "Neither";22 }23 24 private:25 static inline string validIPv6Chars = "0123456789abcdefABCDEF";26 27 bool isIPv4(const string& digit) {28 if (digit.empty() || digit.length() > 3)29 return false;30 if (digit.length() > 1 && digit[0] == '0')31 return false;32 33 for (const char c : digit)34 if (c < '0' || c > '9')35 return false;36 37 const int num = stoi(digit);38 return 0 <= num && num <= 255;39 }40 41 bool isIPv6(const string& digit) {42 if (digit.empty() || digit.length() > 4)43 return false;44 45 for (const char c : digit)46 if (validIPv6Chars.find(c) == string::npos)47 return false;48 49 return true;50 }51};52