LeetCode 468: Validate IP Address Solution
Master LeetCode problem 468 (Validate IP Address), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
468. Validate IP Address
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Check if the input IP address is a valid IPv4 address by splitting the string using the dot delimiter and verifying each part.
- Check if the input IP address is a valid IPv6 address by splitting the string using the colon delimiter and verifying each part.
- Return "IPv4" if the IP address is valid for IPv4, "IPv6" if the IP address is valid for IPv6, and "Neither" if it is not valid for either.
:
Solution Code
class Solution {
public String validIPAddress(String IP) {
if (IP.chars().filter(ch -> ch == '.').count() == 3) {
return validateIPv4(IP) ? "IPv4" : "Neither";
}
if (IP.chars().filter(ch -> ch == ':').count() == 7) {
return validateIPv6(IP) ? "IPv6" : "Neither";
}
return "Neither";
}
private boolean validateIPv4(String ip) {
String[] parts = ip.split("\\.");
if (parts.length != 4) {
return false;
}
for (String part : parts) {
if (part.isEmpty() || part.length() > 3 || (part.charAt(0) == '0' && part.length() > 1)) {
return false;
}
for (char ch : part.toCharArray()) {
if (!Character.isDigit(ch)) {
return false;
}
}
int num = Integer.parseInt(part);
if (num < 0 || num > 255) {
return false;
}
}
return true;
}
private boolean validateIPv6(String ip) {
String[] parts = ip.split(":");
if (parts.length != 8) {
return false;
}
for (String part : parts) {
if (part.isEmpty() || part.length() > 4) {
return false;
}
for (char ch : part.toCharArray()) {
if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) {
return false;
}
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 468 (Validate IP Address)?
This page provides optimized solutions for LeetCode problem 468 (Validate IP Address) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 468 (Validate IP Address)?
The time complexity for LeetCode 468 (Validate IP Address) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 468 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 468 in Java, C++, or Python.