题解 | 验证IP地址

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public static final  String res =  "Neither";
    public String solve (String IP) {
        if (IP.isEmpty()) {
            return res;
        }
        // 先判断是ipv4还是ipv6
        // 再使用特定符号切割,v4切完数组长度为4,v6切完长度为8
        // 遍历数组,根据v4和v6写不同的判断子方法
        boolean isIpv4 = IP.contains("."); // true是ipv4,false是ipv6
        if (isIpv4) {
            String[] ips = IP.split("\\.",-1);
            return checkIpv4(ips);
        } else {
            String[] ips = IP.split("\\:",-1);
            return checkIpv6(ips);
        }
    }

    public String checkIpv4(String[] ips) {
        int n = ips.length;
        if (n != 4) {
            return res;
        }
        for (int i = 0; i < n; i++) {
            String curr = ips[i];
            if (curr.startsWith("0")) {
                return res;
            }
            int num;
            try {
                num = Integer.parseInt(curr);
            } catch (Exception e) {
                return res;
            }
            if (num > 255 || num < 0) {
                return res;
            }
        }
        return "IPv4";
    }

    public String checkIpv6(String[] ips) {
        int n = ips.length;
        if (n != 8) {
            return res;
        }
        for(String ip : ips){
            if(ip.length() > 4 || ip.length() <= 0){
                return res;
            }
            try{
                int val = Integer.parseInt(ip,16);
            }catch(Exception e){
                return res;
            }
        }
        return "IPv6";
    }
}

三个注意点:

1、使用String的split方法时,注意第一个参数为正则表达式regex,遇到特殊字符需要转义

2、使用String的split方法时,注意第二个参数limit,如果不传,则默认为0,注意区分该参数的三种情况

  • 为0时,则表示使用正则式可以尽最大可能切分,丢弃掉为空的项。表明结果数组中不会存在空值
  • 大于0时,按照传递的次数对字符串切分为多少段,剩余的即使包含正则字符的项,也不切,单独成为一项。表明结果数组中可能存在未充分切割的项
  • 小于0时,则表示使用正则式可以尽最大可能切分,为空的项也不丢弃。表明结果数组中会存在空值

3、Integer的parseInt方法第二参数为解析字符串时使用的基数,默认为10,最小为2,最大为36,可以指定

全部评论

相关推荐

驼瑞驰_招募评论官版...:把对方打入公司库是吧
点赞 评论 收藏
分享
09-01 21:40
已编辑
同济大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务