Skip to content

468. Validate IP Address 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
 public:
  string validIPAddress(string IP) {
    string digit;
    istringstream iss(IP);

    if (count(begin(IP), end(IP), '.') == 3) {
      for (int i = 0; i < 4; ++i)  // make sure we have 4 parts
        if (!getline(iss, digit, '.') || !isIPv4(digit))
          return "Neither";
      return "IPv4";
    }

    if (count(begin(IP), end(IP), ':') == 7) {
      for (int i = 0; i < 8; ++i)  // make sure we have 8 parts
        if (!getline(iss, digit, ':') || !isIPv6(digit))
          return "Neither";
      return "IPv6";
    }

    return "Neither";
  }

 private:
  static inline string validIPv6Chars = "0123456789abcdefABCDEF";

  bool isIPv4(const string& digit) {
    if (digit.empty() || digit.length() > 3)
      return false;
    if (digit.length() > 1 && digit[0] == '0')
      return false;

    for (const char c : digit)
      if (c < '0' || c > '9')
        return false;

    const int num = stoi(digit);
    return 0 <= num && num <= 255;
  }

  bool isIPv6(const string& digit) {
    if (digit.empty() || digit.length() > 4)
      return false;

    for (const char c : digit)
      if (validIPv6Chars.find(c) == string::npos)
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
  public String validIPAddress(String IP) {
    if (IP.chars().filter(c -> c == '.').count() == 3) {
      for (final String digit : IP.split("\\.", -1))
        if (!isIPv4(digit))
          return "Neither";
      return "IPv4";
    }

    if (IP.chars().filter(c -> c == ':').count() == 7) {
      for (final String digit : IP.split("\\:", -1))
        if (!isIPv6(digit))
          return "Neither";
      return "IPv6";
    }

    return "Neither";
  }

  private static final String validIPv6Chars = "0123456789abcdefABCDEF";

  private boolean isIPv4(final String digit) {
    if (digit.isEmpty() || digit.length() > 3)
      return false;
    if (digit.length() > 1 && digit.charAt(0) == '0')
      return false;

    for (final char c : digit.toCharArray())
      if (c < '0' || c > '9')
        return false;

    final int num = Integer.parseInt(digit);
    return 0 <= num && num <= 255;
  }

  private boolean isIPv6(final String digit) {
    if (digit.isEmpty() || digit.length() > 4)
      return false;

    for (final char c : digit.toCharArray())
      if (!validIPv6Chars.contains("" + c))
        return false;

    return true;
  }
}
Back to top