题目:
468. Validate IP Address(medium)
解题思路:
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public String validIPAddress(String IP) { if(IP == null || IP.length() == 0) return "Neither"; String[] IP4Addr = IP.split("\\.",-1);//-1会保留空值 if(IP4Addr.length == 4){ return isIP4Addr(IP4Addr); }
String[] IP6Addr = IP.split(":",-1); if(IP6Addr.length == 8){ return isIP6Addr(IP6Addr); }
return "Neither"; }
private String isIP4Addr(String[] IP4Addr){ for(String ip : IP4Addr){ if(ip.length() > 3 || ip.length() <= 0){ return "Neither"; } for(int i = 0;i < ip.length();++i){ if(!Character.isDigit(ip.charAt(i))){ return "Neither"; } } int num = Integer.parseInt(ip); if(num > 255 || String.valueOf(num).length() != ip.length()){ return "Neither"; } } return "IPv4"; }
private String isIP6Addr(String[] IP6Addr){ for(String ip : IP6Addr){ if(ip.length() > 4 || ip.length() <= 0){ return "Neither"; } for(int i = 0;i < ip.length();i++){ char c = ip.charAt(i); if(!Character.isDigit(c) && !('a' <= c && c <= 'f' ) && !('A' <= c && c <= 'F')){ return "Neither"; } } } return "IPv6"; }
|
v1.5.2