一开始就想到正则表达式,但还是老老实实写了
import java.util.*;
import java.lang.*;
public class Solution {
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
public String solve (String IP) {
// write code here
if(isIPv4(IP))return "IPv4";
else if(isIPv6(IP)){return "IPv6";}
else return "Neither";
}
public boolean isIPv4(String IP){
String[] str = IP.split("\\.");
if(str.length<4)return false;
for(int i=0;i<str.length;i++){
if(str[i].startsWith("0"))return false;
try{
Integer num =Integer.parseInt(str[i]);
if(num>255)return false;
}catch(Exception e){
return false;
}
}
return true;
}
public boolean isIPv6(String IP){
if(IP.endsWith(":") || IP.startsWith(":"))return false;
String[] str = IP.split("\\:");
if(str.length<8)return false;
for(int i=0;i<str.length;i++){
if(str[i].length()==0 || str[i].length()>4)return false;
for(int j=0;j<str[i].length();j++){
char c = str[i].charAt(j);
boolean exp = (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
if(!exp)return false;
}
}
return true;
}
}