力扣468. 验证IP地址

力扣每日一题哈。

验证是否是一个正确的IP地址。

思路:

  1. 首先,把这个题细分一下,判断他是否是一个IPV4地址,或者ipv6地址。
  2. 然后判断IPV4和ipv6是否是有效的。

具体代码如下:


/**
 * @author xnl
 * @Description:
 * @date: 2022/5/29   20:15
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        // String queryIP = "172.16.254.10";
        //String queryIP = "2001:0db8:85a3:0:0:8A2E:0370:0";
//        String queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334:";
//        String queryIP = "12..33.4";
        String queryIP = "20EE:FGb8:85a3:0:0:8A2E:0370:7334";
        System.out.println(solution.validIPAddress(queryIP));
    }

    public String validIPAddress(String queryIP) {
        // 是一个ipv4的地址
        if (queryIP.contains(".")){
            return isIpv4(queryIP);
        } else {
            return isIpv6(queryIP);
        }
    }

    /**
     * 是否是一个有效的IPV4地址
     * @param queryIP
     * @return
     */
    private String isIpv4(String queryIP){
        String[] split = queryIP.split("\\.");
        if (split.length != 4  || queryIP.charAt(queryIP.length() - 1) == '.'){
            return "Neither";
        }

        for (String str : split){
            if (!isIpv4Int(str)){
                return "Neither";
            }
        }
        return "IPv4";
    }

    /**
     * 是否是一个有效的IPV4整数
     */
    private boolean isIpv4Int (String str){
        int length = str.length();
        // 去除首字母为空的情况
        if (str.isEmpty() || (length > 1 && str.charAt(0) == '0')){
            return false;
        }

        int temp = 0;
        for (int i = 0; i < length; i++){
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                temp = temp * 10 + (str.charAt(i) - '0');
            }else {
                return false;
            }
        }
        return temp >= 0 && temp <= 255;
    }

    /**
     * 是否是一个有效的IPv6地址
     * @param queryIP
     * @return
     */
    private String isIpv6(String queryIP){
        String[] split = queryIP.split("\\:");

        if (split.length != 8 || queryIP.charAt(queryIP.length() - 1) == ':'){
            return "Neither";
        }

        for (String str : split) {
            if (!isIpv6Int(str)){
                return "Neither";
            }
        }
        return "IPv6";
    }

    private boolean isIpv6Int(String str){
        if (str.isEmpty() || str.length() > 4){
            return false;
        }

        for (int i = 0; i < str.length(); i++){
            if (!((str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'f') ||
                    (str.charAt(i) >= 'A' && str.charAt(i) <= 'F'))){
                return false;
            }
        }
        return true;
    }
}

如果有兴趣一起刷题的可以私聊我哈,一起学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值