题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
public String solve (String IP) {
// write code here
if(IP.charAt(0) == '.' || IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == '.' || IP.charAt(IP.length()-1) == ':')
return "Neither";
if (IP.contains(".")) {
String[] ip = IP.split("\\.");
if (ip.length != 4 ) {
return "Neither";
} else {
for (String str : ip) {
if (str.length() > 3 || str.charAt(0) == '0') {
return "Neither";
} else {
try{
if(Integer.parseInt(str) >= 256){
return "Neither";
}}catch(Exception e){
return "Neither";
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9' ) {
continue;
} else {
return "Neither";
}
}
}
}
return "IPv4";
}
}
if (IP.contains(":")) {
String[] ip6 = IP.split(":");
if (ip6.length != 8) {
return "Neither";
} else {
int index = -1;
for (String str : ip6) {
if(str.contains("00")){
index = str.indexOf("00");
}
if ((str.contains("00") && (index == 0) )|| str.length() < 1 || str.length() > 4 || str.isEmpty()) {
return "Neither";
} else {
for (int i = 0; i < str.length(); i++) {
if (!(str.charAt(i) >= 'a' && str.charAt(i) <= 'f' || str.charAt(i) >= 'A' && str.charAt(i) <= 'F' || str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
return "Neither";
}
}
}
}
return "IPv6";
}
}
return "Neither";
}
}