题解 | #验证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(ipv4(IP))
return "IPv4";
if(ipv6(IP))
return "IPv6";
return "Neither";
}
private Boolean ipv6(String IP){
if(IP.startsWith(":") || IP.endsWith(":")){
System.out.println("不能根据规则划分");
return false;
}
String[] strs = IP.split(":");
if(strs.length != 8){
System.out.println("不能根据规则划分");
return false;
}
for(int i = 0; i < strs.length; i++){
if(strs[i].equals("0")){
continue;
}
if(strs[i].length() == 0 || strs[i].length() > 4){
System.out.println("不可省略");
return false;
}
for(int j = 0; j < strs[i].length(); j++){
if(!legalChar(strs[i].charAt(j))){
System.out.println("字符不合法");
return false;
}
}
}
return true;
}
private Boolean legalChar(char c){
if(c <= '9' && c >= '0')
return true;
if(c <= 'e' && c >= 'a')
return true;
if(c <= 'E' && c >= 'A')
return true;
return false;
}
private Boolean ipv4(String IP){
if(IP.startsWith(".") || IP.endsWith(".")){
System.out.println("不能根据规则划分");
return false;
}
String[] strs = IP.split("\\.");
if(strs.length != 4){
System.out.println("不能根据规则划分");
return false;
}
for(int i = 0; i < 4; i++){
if(strs[i].length() > 1 && strs[i].startsWith("0"))
return false;
try{
int temp = Integer.valueOf(strs[i]);
if(temp < 0 || temp > 255)
return false;
}catch(Exception e){
e.printStackTrace();
System.out.println("报错了");
return false;
}
}
return true;
}
}
查看15道真题和解析