468. Validate IP Address

https://leetcode.com/problems/validate-ip-address/

检查str是否是合法的IPv4或v6地址。v4地址被.隔出四段,每段是个十进制整数,范围为0~255,且非0数不应以0开头,为0时应只有一个数字。v6被:隔出8段,每段是个长度为4的16进制数。

class Solution {
    private boolean isIPv4(String s) {
        try {
            int v = Integer.valueOf(s);
            if (v == 0 && s.length() > 1) return false;
            else if (v == 0) return true;
            if (v > 0 && v <= 255 && !s.startsWith("0")) return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    
    private boolean isIPv6(String s) {
        if (s.length() > 4) return false;
        try {
            int v = Integer.parseInt(s, 16);
            if (v >= 0 && s.charAt(0) != '-') return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    
    public String validIPAddress(String IP) {
        if (IP.chars().filter(ch -> ch == '.').count() == 3) {
            for (String s : IP.split("\\.", -1)) {
                if (!isIPv4(s)) return "Neither";
            }
            return "IPv4";
        }
        if (IP.chars().filter(ch -> ch == ':').count() == 7) {
            for (String s : IP.split("\\:", -1)) {
                if (!isIPv6(s)) return "Neither";
            }
            return "IPv6";
        }
        return "Neither";
    }
}

Last updated