Very easy to understand Java Solution with a little regex


  • 0
    R

    For IPv4, we need to matches all digits:

    s.matches("\\d+");
    

    For IPv6, we need to matches digits and alphabets, which can be 1 to 4 characters:

    s.matches("[0-9a-fA-F]"{1,4});
    

    {1,4} means the number of characters is from 1 to 4.

        public String validIPAddress(String IP) {
            if (IP == null || IP.length() == 0) return "Neither";
            if (isValidIPv4(IP))
                return "IPv4";
            if (isValidIPv6(IP))
                return "IPv6";
            return "Neither";
        }
    
        private boolean isValidIPv4(String IP) {
            // if the last character is not digit, return false. It handles the input like "0.0.0.0." which has a dot
            // in the end and the following split function cannot handle this dot.
            if (!Character.isDigit(IP.charAt(IP.length() - 1)))
                return false;
            String[] groups = IP.split("\\.");
            // must have 4 groups of digits
            if (groups.length != 4) return false;
            for (String s : groups) {
                // all character should be digits
                if (!s.matches("\\d+")) return false;
                // handle other invalid inputs
                if (s.length() > 3 || s.length() == 0 || (s.charAt(0) == '0' && s.length() > 1) || Integer.parseInt(s) > 255)
                    return false;
            }
            return true;
        }
    
        private boolean isValidIPv6(String IP) {
            if (!(IP.charAt(IP.length() - 1) + "").matches("[0-9a-fA-F]")) return false;
            String[] groups = IP.split(":");
            if (groups.length != 8) return false;
            for (String s : groups) {
                if (!s.matches("[0-9a-fA-F]{1,4}")) return false;
            }
            return true;
        }
    

Log in to reply
 

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