Java Solution


  • 0

    Without regex...

    public class Solution {
        public String validIPAddress(String IP) {
            if (validateIPv4(IP)) {
                return "IPv4";
            }
            if (validateIPv6(IP)) {
                return "IPv6";
            }
            return "Neither";
        }
        
        private boolean validateIPv4(String IP) {
            String[] strs = IP.split("\\.", -1);
            if (strs.length != 4) {
                return false;
            }
            
            for (String str : strs) {
                int len = str.length();
                if (len < 1 || len > 3 || (len > 1 && str.charAt(0) == '0')) {
                    return false;
                }
                for (char c : str.toCharArray()) {
                    if (!Character.isDigit(c)) {
                        return false;
                    }
                }
                if (Integer.parseInt(str) > 255) {
                    return false;
                }
            }
            
            return true;
        }
        
        private boolean validateIPv6(String IP) {
            String[] strs = IP.toLowerCase().split(":", -1);
            if (strs.length != 8) {
                return false;
            }
            
            for (String str : strs) {
                int len = str.length();
                if (len < 1 || len > 4) {
                    return false;
                }
                for (char c : str.toCharArray()) {
                    if (!Character.isDigit(c) && (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.