题解 | #验证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(isIPv4(IP)){ return "IPv4"; }else if(isIPv6(IP)){ return "IPv6"; }else{ return "Neither"; } } Boolean isIPv4(String IP){ String []strs = IP.split("\\.", -1); if(strs.length != 4) return false; for(int i = 0; i < 4; i++){ // validate str[i] int len = strs[i].length(); if(len == 0) return false; if(len > 1 && strs[i].charAt(0) == '0') return false; for(int j = 0; j < len; j++){ if(strs[i].charAt(j) < '0' || strs[i].charAt(j) > '9') return false; } if(len >= 1){ int num = Integer.valueOf(strs[i]); if(num < 0 || num > 255) return false; } } return true; } Boolean isIPv6(String IP){ String []strs = IP.split("\\:", -1); if(strs.length != 8) return false; for(int i = 0; i < 8; i++){ // validate str[i] int len = strs[i].length(); if(len == 0 || len > 4) return false; for(int j = 0; j < len; j++){ if(strs[i].charAt(j) >= '0' && strs[i].charAt(j) <= '9' || strs[i].charAt(j) >= 'A' && strs[i].charAt(j) <= 'F' || strs[i].charAt(j) >= 'a' && strs[i].charAt(j) <= 'f' ) continue; else return false; } } return true; } }