Simple short solution


  • 1
    S
    public String validIPAddress(String IP) {
       if (IP.contains(".")){
           if (IP.charAt(0) == '.' || IP.charAt(IP.length()-1) == '.') return "Neither";
           String[] strs = IP.split("\\.");
           if (strs.length == 4) {
               for (String s : strs) {
                   if (s.length() == 0 || s.length() >4 || s.length()>1 && s.charAt(0) == '0') 
                       return "Neither";
                   for (char c : s.toCharArray()) if (!Character.isDigit(c)) return "Neither";
                   if (Integer.valueOf(s) > 255) return "Neither";
               }
               return "IPv4";
           }
       }else if (IP.contains(":")) {
           if (IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == ':') return "Neither";
           String[] strs = IP.split(":");
           if (strs.length == 8) {
               for (String s : strs) {
                   if (s.length() == 0 || s.length() >4) return "Neither";
                   for (char c : s.toCharArray()) 
                      if (!Character.isDigit(c) && (c-'a'<0 || c-'f'>0) && (c-'A'<0 || c-'F'>0)) 
                           return "Neither";
               }
               return "IPv6";
           }
       }
       return "Neither";
    }
    

Log in to reply
 

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