JAVA solution simple but covers a few extra cases.


  • 0
    S
        public String validIPAddress(String IP) {
            if(IP.length() == 0)
                return "Neither";
            String ipv4[] = IP.split("\\.");
            String ipv6[] = IP.split(":");
            if(ipv4.length != 4 && ipv6.length != 8)
                return "Neither";
            if(ipv4.length == 4)
                return checkIpv4(ipv4,IP);
            else
                return checkIpv6(ipv6,IP);
        }
        private String checkIpv4(String arr[], String s) {
            if(s.charAt(s.length() - 1) == '.')
                return "Neither";
            for(int i = 0; i < arr.length; i++) {
                String val = arr[i];
                if(val.length() == 0)
                    return "Neither";
                if(val.charAt(0) == '0' && val.length() != 1)
                    return "Neither";
                if(val.length() > 3)
                    return "Neither";
                for(int j = 0; j < val.length(); j++) {
                    if(val.charAt(j) >= '0' && val.charAt(j) <= '9')
                        continue;
                    else
                        return "Neither";
                }
                int value = Integer.parseInt(val);
                if(value < 0 || value > 255)
                    return "Neither";
            }
            return "IPv4";
        }
        private String checkIpv6(String arr[], String s) {
                    if(s.charAt(s.length() - 1) == ':')
                return "Neither";
            for(int i = 0; i < arr.length; i++) {
                String val = arr[i];
                if(val.length() == 0)
                    return "Neither";
                if(val.length() > 4)
                    return "Neither";
                for(int j = 0; j < val.length(); j++) {
                    char ch = val.charAt(j);
                    if((val.charAt(j) >= '0' && val.charAt(j) <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))
                        continue;
                    else
                        return "Neither";
                }
            }
            return "IPv6";
        }
        
    }

Log in to reply
 

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