Java 37line solution


  • 0
    S
    public class Solution {
        public String validIPAddress(String IP) {
            // special case when begin or end is '.' or ':'
            if (IP.length() >= 1 && (IP.charAt(0) =='.' || IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == '.' || IP.charAt(IP.length()-1) == ':')) return "Neither";
            String[] v4 = IP.split("\\.");
            if (v4.length == 4){
                for (String ele: v4){
                    // check length
                    if (ele.length() == 0 || ele.length() > 3) return "Neither";
                    // check leading zero
                    if (ele.length() > 1 && ele.charAt(0) == '0')return "Neither";
                    for (char c: ele.toCharArray()){
                        if (c >= '0' && c <= '9') continue;
                        else return "Neither";
                    }
                    int check = Integer.parseInt(ele);
                    if (check > 255 || check < 0) return "Neither";
                }
                return "IPv4";
            }
            String [] v6 = IP.split(":");
            if (v6.length == 8){
                for (String ele: v6){
                    // check length >0 , length <=4
                    if (ele.length() > 4 || ele.length() ==0) return "Neither";
                    ele = ele.toUpperCase();
                    for (char c: ele.toCharArray()){
                        if (c == 'A' || c == 'B' || c == 'C' || c == 'D' || c == 'E' || c == 'F' || (c >= '0' && c <= '9'))
                            continue;
                        else 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.