Given a string IP
, return "IPv4"
if IP is a valid IPv4 address, "IPv6"
if IP is a valid IPv6 address or "Neither"
if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4"
where 0 <= xi <= 255
and xi
cannot contain leading zeros. For example, "192.168.1.1"
and "192.168.1.0"
are valid IPv4 addresses but "192.168.01.1"
, while "192.168.1.00"
and "192.168@1.1"
are invalid IPv4 addresses.
A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8"
where:
1 <= xi.length <= 4
xi
is a hexadecimal string which may contain digits, lower-case English letter ('a'
to'f'
) and upper-case English letters ('A'
to'F'
).- Leading zeros are allowed in
xi
.
Example 1:
Input: IP = "172.16.254.1" Output: "IPv4"
Approach
Java
public class ValidateIPAddress {public static void main(String[] args) {String IP = "20EE:FGb8:85a3:0:0:8A2E:0370:7334";System.out.println(validIPAddress(IP));}private static final String IPv6 = "IPv6";private static final String IPv4 = "IPv4";private static final String Neither = "Neither";public static String validIPAddress(String IP) {if (IP == null || IP.length() == 0)return Neither;boolean hasDots = IP.indexOf('.') != -1;boolean hasColons = IP.indexOf(':') != -1;if (!(hasDots ^ hasColons))return Neither;if (hasDots)return validateV4(IP);return validateV6(IP);}private static String validateV4(String ip) {if (ip.endsWith("."))return Neither;String[] arr = ip.split("\\.");if (arr.length != 4)return Neither;for (String sub : arr) {if (sub.length() > 1 && sub.startsWith("0"))return Neither;try {int num = Integer.parseInt(sub);if (num < 0 || num > 255)return Neither;} catch (NumberFormatException nfe) {return Neither;}}return IPv4;}private static String validateV6(String ip) {if (ip.endsWith(":"))return Neither;String[] arr = ip.split("\\:");if (arr.length != 8)return Neither;for (String sub : arr) {if (sub.length() < 1 || sub.length() > 4)return Neither;try {Integer.parseInt(sub, 16);} catch (NumberFormatException nfe) {return Neither;}}return IPv6;}}
C++
#include <bits/stdc++.h>using namespace std;string validIPAddress(string IP){stringstream s(IP);string temp;int cnt = 0;if (IP.find(":") == string ::npos){while (getline(s, temp, '.')){cnt++;if (cnt > 4 || temp.size() > 3 || temp.size() == 0 ||(temp.size() > 1 && temp[0] == '0'))return "Neither";for (int i = 0; i < temp.size(); i++){if (temp[i] > '9' || temp[i] < '0')return "Neither";int x = stoi(temp);if (x > 255 || x < 0)return "Neither";}}return (cnt == 4 && IP.back() != '.') ? "IPv4" : "Neither";}else{while (getline(s, temp, ':')){cnt++;if (cnt > 8 || temp.size() == 0 || temp.size() > 4)return "Neither";for (int i = 0; i < temp.size(); i++){if (!(temp[i] >= '0' && temp[i] <= '9') &&!(temp[i] >= 'a' && temp[i] <= 'f') && !(temp[i] >= 'A'&& temp[i] <= 'F'))return "Neither";}}return (cnt == 8 && IP.back() != ':') ? "IPv6" : "Neither";}}int main(){string IP = "172.16.254.1";cout << validIPAddress(IP);return 0;}
No comments:
Post a Comment