Simple Java Solution


  • 0
    A
    class Solution {
        private static final String NEITHER = "Neither";
        private static final String IPV4 = "IPv4";
        private static final String IPV6 = "IPv6";
    
        public String validIPAddress(final String ip) {
            if (ip == null || ip.length() < 7 ||
                    ip.startsWith(".") || ip.endsWith(".") ||
                    ip.startsWith(":") || ip.endsWith(":")) {
                return NEITHER;
            }
    
            boolean containsDot = false, containsColon = false;
            for (int i = 0; i < ip.length(); i++) {
                if (ip.charAt(i) == '.') {
                    containsDot = true;
                    break;
                } else if (ip.charAt(i) == ':') {
                    containsColon = true;
                    break;
                }
            }
    
            if (containsDot) {
                return validateIpV4(ip);
            } else if (containsColon) {
                return validateIpV6(ip);
            } else {
                return NEITHER;
            }
        }
    
        private String validateIpV6(final String ip) {
            String[] tokens = ip.split(":");
            if (tokens.length != 8) {
                return NEITHER;
            }
    
            for (String token : tokens) {
                if (token.length() < 1 || token.length() > 4) {
                    return NEITHER;
                }
                if (!token.matches("[a-fA-F0-9]{1,4}")) {
                    return NEITHER;
                }
            }
    
            return IPV6;
        }
    
        private String validateIpV4(final String ip) {
            String[] tokens = ip.split("\\.");
            if (tokens.length != 4) {
                return NEITHER;
            }
    
            for (String token : tokens) {
                if (token.length() < 1 || token.length() > 3 ||
                        (token.charAt(0) == '0' && token.length() > 1) || token.charAt(0) == '+' || token.charAt(0) == '-') {
                    return NEITHER;
                } else {
                    try {
                        if (Integer.parseInt(token) > 255) {
                            return NEITHER;
                        }
                    } catch (final NumberFormatException ex) {
                        return NEITHER;
                    }
                }
            }
    
            return IPV4;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.