Leetcode 468. Validate IP Address
Given a string queryIP
, return “IPv4” if queryIP
is a valid IPv4 address, “IPv6” if queryIP
is a valid IPv6 address or “Neither” if queryIP
is not a correct IP of either type.
An IPv4 address is an address consisting of four numbers separated by dots, where each number is between 0 and 255 (inclusive) and cannot have leading zeros. Additionally, it’s a valid IPv4 address if and only if all four numbers are between 0 and 255 inclusive.
An IPv6 address is an address consisting of eight groups of four hexadecimal digits separated by colons. Each group is written using only hexadecimal digits (0-9, a-f, A-F) and can’t be empty.
Example:
Input: queryIP = "172.16.254.1"
Output: "IPv4"
Input: queryIP = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
Output: "IPv6"
Input: queryIP = "256.256.256.256"
Output: "Neither"
.
).:
).#include <iostream>
#include <sstream>
#include <vector>
#include <cctype>
class Solution {
public:
std::string validIPAddress(std::string queryIP) {
if (isIPv4(queryIP)) return "IPv4";
if (isIPv6(queryIP)) return "IPv6";
return "Neither";
}
private:
bool isIPv4(const std::string& ip) {
std::vector<std::string> parts = split(ip, '.');
if (parts.size() != 4) return false;
for (const std::string& part : parts) {
if (part.empty() || part.size() > 3) return false;
for (char c : part) {
if (!isdigit(c)) return false;
}
int num = stoi(part);
if (num < 0 || num > 255 || std::to_string(num) != part) return false;
}
return true;
}
bool isIPv6(const std::string& ip) {
std::vector<std::string> parts = split(ip, ':');
if (parts.size() != 8) return false;
for (const std::string& part : parts) {
if (part.empty() || part.size() > 4) return false;
for (char c : part) {
if (!isxdigit(c)) return false;
}
}
return true;
}
std::vector<std::string> split(const std::string& s, char delim) {
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
};
This solution thus efficiently checks the validity of the given IP address.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?