← Home

468. Validate IP Address

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
468

Let's make this one less mysterious. For 468. Validate IP Address, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isnum, isalnum, ishex, string_split, validIPAddress.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 4 ms, faster than 37.03% of C++ online submissions for Validate IP Address.
02//Memory Usage: 6.3 MB, less than 82.33% of C++ online submissions for Validate IP Address.
03class Solution {
04public:
05    bool isnum(std::string s){
06        return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
07    };
08    
09    bool isalnum(std::string s){
10        return !s.empty() && std::all_of(s.begin(), s.end(), [](const char c){return std::isalnum(c);});
11    };
12    
13    bool ishex(std::string s){
14        return !s.empty() && s.find_first_not_of("0123456789abcdef") == std::string::npos;
15    };
16    
17    std::vector<std::string> string_split(std::string str, std::string delimiter){
18        size_t pos = 0;
19        std::string token;
20        std::vector<std::string> result;
21        while(true){
22            pos = str.find(delimiter);
23            //works even if pos is string::npos
24            token = str.substr(0, pos);
25            result.push_back(token);
26            if(pos == string::npos) break;
27            //pos+1 equals to 0, so the line below can't handle this situation
28            str.erase(0, pos+delimiter.length());
29        }
30        return result;
31    }
32    
33    string validIPAddress(string IP) {
34        if(IP.find(".") != string::npos){
35            if(count(IP.begin(), IP.end(), '.') != 3)
36                return "Neither";
37            vector<string> tokens = string_split(IP, ".");
38            for(string token : tokens){
39                if(token.size() > 3){
40                    return "Neither";
41                }else if(!isnum(token)){
42                    return "Neither";
43                }else if(token.rfind("0", 0) == 0 && token.size() > 1){
44                    return "Neither";
45                }else{
46                    int num = stoi(token);
47                    if(num < 0 || num > 255) return "Neither";
48                }
49            }
50            return "IPv4";
51        }else if(IP.find(":") != string::npos){
52            if(count(IP.begin(), IP.end(), ':') != 7)
53                return "Neither";
54            std::transform(IP.begin(), IP.end(), IP.begin(), 
55                           [](unsigned char c){return std::tolower(c);});
56            vector<string> tokens = string_split(IP, ":");
57            for(string token : tokens){
58                if(token.size() == 0 || token.size() > 4){
59                    return "Neither";
60                }else if(!ishex(token)){
61                    return "Neither";
62                }
63            }
64            return "IPv6";
65        }
66        
67        return "Neither";
68    }
69};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.