力扣468 验证IP地址

需要注意的点:

xi 是一个 十六进制字符串 ,可以包含数字、小写英文字母( 'a'到 'f' )和大写英文字母( 'A' 到 'F' )。

这个条件可以根据ASCii码写成:

if(c<'0'||c>'9'&&c<'A'||c>'F'&&c<'a'||c>'f'){
                    return false;
                }

 因为ASCii码如下:

public String validIPAddress(String queryIP) {
        if(queryIP.indexOf('.')>0){
            return isIPv4(queryIP)?"IPv4":"Neither";
        }
        else {
            return isIPv6(queryIP)?"IPv6":"Neither";
        }
    }

   private boolean isIPv4(String queryIP) {
        String[] arr = queryIP.split("\\.",-1);
        int len = arr.length;
        if(len!=4) return false;
        for (int i = 0; i < len; i++) {
            String temp = arr[i];
            if(temp.length()==0||temp.length()>3) return false;
            if (temp.length() > 1 && temp.charAt(0) == '0') {
                return false;
            }
            for (int k = 0; k < temp.length(); k++) {
                char c = temp.charAt(k);
                if (!Character.isDigit(c)) {
                    return false;
                }
            }
            int number = Integer.parseInt(temp);
            if (number < 0 || number > 255) {
                return false;
            }
        }
        return true;
    }

    private boolean isIPv6(String queryIP){
        String[] arr = queryIP.split(":",-1);
        int len = arr.length;
        if(len!=8) return false;
        for(int i=0;i<len;i++){
            String temp=arr[i];
            if(temp.length()<1||temp.length()>4){
                return false;
            }
            for(int k=0;k<temp.length();k++){
                char c=temp.charAt(k);
                if(c<'0'||c>'9'&&c<'A'||c>'F'&&c<'a'||c>'f'){
                    return false;
                }
            }
        }
        return true;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值