Created
February 16, 2020 02:11
-
-
Save wushbin/bd26a78915b99fe1a582a6a33cbaacfa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String validIPAddress(String IP) { | |
String[] ipv4 = IP.split("\\."); | |
String[] ipv6 = IP.split("\\:"); | |
if (ipv4.length == 4) { | |
if (countSep(IP, '.') > 3) { | |
return "Neither"; | |
} | |
for (int i = 0; i < 4; i++) { | |
if (!isIPV4(ipv4[i])) { | |
return "Neither"; | |
} | |
} | |
return "IPv4"; | |
} | |
if (ipv6.length == 8) { | |
if (countSep(IP, ':') > 7) { | |
return "Neither"; | |
} | |
for (int i = 0; i < 8; i++) { | |
if (!isIPV6(ipv6[i])) { | |
return "Neither"; | |
} | |
} | |
return "IPv6"; | |
} | |
return "Neither"; | |
} | |
private int countSep(String s, char c) { | |
int cnt = 0; | |
for (char ch : s.toCharArray()) { | |
if (ch == c) { | |
cnt += 1; | |
} | |
} | |
return cnt; | |
} | |
private boolean isIPV4(String s) { | |
if (s == null || s.length() == 0) { | |
return false; | |
} | |
int len = s.length(); | |
if (len > 3 || len > 1 && s.charAt(0) == '0') { | |
return false; | |
} | |
int num = 0; | |
for (int i = 0; i < len; i++) { | |
char curr = s.charAt(i); | |
if (curr < '0' || curr > '9') { | |
return false; | |
} | |
num = num * 10 + (s.charAt(i) - '0'); | |
if (num > 255) { | |
return false; | |
} | |
} | |
return num >= 0 && num < 256; | |
} | |
private boolean isIPV6(String s) { | |
if (s == null || s.length() == 0) { | |
return false; | |
} | |
int len = s.length(); | |
if (len > 4) { | |
return false; | |
} | |
for (int i = 0; i < len; i++) { | |
if (!isValid(s.charAt(i))) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private boolean isValid(char c) { | |
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment