Java solution - be careful about all details


  • 0
    D
    public class Solution {
        private static String IPv4 = "IPv4";
        private static String IPv6 = "IPv6";
        private static String NEITHER = "Neither";
    
        public String validIPAddress(String IP) {
            if (IP == null || IP.length() == 0) {
                return NEITHER;
            }
            return isIPv4(IP) ? IPv4 : (isIPv6(IP) ? IPv6 : NEITHER);
        }
    
        private boolean isIPv4(String IP) {
            String[] parts = IP.split("\\.");
            if (parts.length != 4 || IP.charAt(IP.length() - 1) == '.') {
                return false;
            }
            for (String part : parts) {
                if (part == null || part.length() == 0 || part.length() > 3) {
                    return false;
                }
                for (int i = 0; i < part.length(); i++) {
                    char c = part.charAt(i);
                    if (c < '0' || c > '9') {
                        return false;
                    }
                }
                char first = part.charAt(0);
                int val = Integer.parseInt(part);
                if (first == '0' && (val != 0 || part.length() > 1)) {
                    return false;
                }
                if (val < 0 || val > 255) {
                    return false;
                }
            }
            return true;
        }
    
        private boolean isIPv6(String IP) {
            String[] parts = IP.split("\\:");
            if (parts.length != 8 || IP.charAt(IP.length() - 1) == ':') {
                return false;
            }
            for (String part : parts) {
                if (part == null || part.length() == 0 || part.length() > 4) {
                    return false;
                }
                for (int i = 0; i < part.length(); i++) {
                    char c = part.charAt(i);
                    if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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