Java solution


  • 0
    J

    this question is pretty easy. don't know why marked as medium.

        public String validIPAddress(String IP) {
            String[] cs = IP.split("\\.");
            if (cs.length == 4) return (IP.charAt(0) != '.') && (IP.charAt(IP.length() - 1) != '.') ? tryIP4(cs) : "Neither";
            else {
                cs = IP.split(":");
                if (cs.length == 8) return (IP.charAt(0) != ':') && (IP.charAt(IP.length() - 1) != ':') ? tryIP6(cs) : "Neither";
                else return "Neither";
            }
        }
        
        private String tryIP4(String[] cs) {
            for (String s : cs) {
                int num = 0;
                if (s.length() == 0 || s.length() > 3 || s.length() > 1 && s.charAt(0) == '0') return "Neither";
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    if (!(c >= '0' && c <= '9')) return "Neither";
                    num = num * 10 + c - '0';
                }
                if (num > 255) return "Neither";
            }
            return "IPv4";
        }
        
        private String tryIP6(String[] cs) {
            for (String s : cs) {
                if (s.length() == 0 || s.length() > 4) return  "Neither";
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    if (!Character.isDigit(c)) {
                        if (!Character.isLetter(c)) return "Neither";
                        c = Character.toUpperCase(c);
                        if (c > 'F') return "Neither";
                    }
                }
            }
            return "IPv6";
        }
    

Log in to reply
 

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