题解 | #验证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) { if (IP.contains(".")) { return isIPV4(IP); } else if (IP.contains(":")) { return isIPV6(IP); } else { return "Neither"; } } /** * 判断是IPV4地址 * 如:172.16.254.1 */ private String isIPV4(String ip) { String[] split = ip.split("\\."); if (split.length != 4) { return "Neither"; } for (String s : split) { if (s.equals("") || (s.length() > 0 && s.startsWith("0"))) { return "Neither"; } int i = 0; try { i = Integer.parseInt(s); } catch (NumberFormatException e) { return "Neither"; } if (i < 0 || i > 255) { return "Neither"; } } return "IPv4"; } /** * 判断是IPV6地址 * 如:2001:0db8:85a3:0:0:8A2E:0370:7334 */ private String isIPV6(String ip) { String[] split = ip.split(":"); if (split.length != 8) { return "Neither"; } if (ip.startsWith(":") || ip.endsWith(":")){ return "Neither"; } for (String s : split) { if (s.length() > 4 || s.length() == 0) { return "Neither"; } final char[] chars = s.toCharArray(); for (char ch : chars) { if (!((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))){ return "Neither"; } } } return "IPv6"; } }