题解 | #验证IP地址#

验证IP地址

http://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

解法

  • ipv4在判断值得时候直接使用Integer,valueOf()方法转为十进制进行范围判断即可,如果捕获到异常说明格式有错误,不符合
  • ipv6在判断字符串长度合适之后直接使用Integer.valueOf(s,16)转为十进制即可,如果捕捉到异常说明格式错误,直接返回false即可

重点:字符串处理还是要多练习,这道题目耗费时间太多

import java.util.*;


public class Solution {
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    public String solve (String IP) {
        // write code here
        if (IP == null || IP.length() == 0) return "Neither";
        if (judgeIpv4(IP)) {
            return "IPv4";
        }
        if (judgeIpv6(IP)) {
            return "IPv6";
        }

        return "Neither";

    }

    public boolean judgeIpv4(String str) {
        String[] temp = str.split("\\.", -1);
        int len = temp.length;
        if (len != 4) return false;

        for (String s : temp) {
            if (s.length() > 1 && s.charAt(0) == '0') {
                return false;
            }
            try {
                int val = Integer.valueOf(s);
                if (!(val >= 0 && val <= 255)) {
                    return false;
                }
            } catch (NumberFormatException e) {
                return false;
            }

        }

        return true;
    }

    public boolean judgeIpv6(String str) {
        String[] temp = str.split(":",-1);
        int len = temp.length;
        if (len != 8) return false;
        for(int i = 0;i < 8;i++){
            String s = temp[i];
            if(s.length()==0 || s.length()>4){
                return false;
            } 
            try{
                int val = Integer.valueOf(s,16);
            }catch(NumberFormatException e){
                return false;
            }
        }
        return true;
    }
}




















全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务