Java Straightforward


  • 0
    C
     public String validIPAddress(String IP) {
             boolean iv4 = false, iv6 = false;
            if(IP.indexOf(".") != -1){
                if(IP.indexOf(":") != -1) return "Neither";
                iv4 = true;
            }
            if(IP.indexOf(":") != -1){
                if(IP.indexOf(".") != -1) return "Neither";
                iv6 = true;
            }
            if(iv4){
                String[] strs = IP.split("\\.");
                if(strs.length != 4 || !Character.isDigit(IP.charAt(IP.length()-1))) return "Neither";
                for(String s : strs){
                    if(s.charAt(0) == '0' && s.length() > 1) return "Neither";
                    if(s.length() > 3) return "Neither";
                    int val = 0,  i = 0;
                    while(i < s.length() && Character.isDigit(s.charAt(i))){
                        val = 10*val + s.charAt(i)-'0';
                        i++;
                    }
                    if(i != s.length()) return "Neither";
                    if(val >= 256 || val < 0) return "Neither";
                }
                return "IPv4";
            }
            if(iv6){
                String[] strs = IP.split(":");
                if(strs.length != 8 || !Character.isLetterOrDigit(IP.charAt(IP.length()-1))) return "Neither";
                for(String s : strs){
                    char[] ch = s.toCharArray();
                    if(ch.length == 0 || ch.length > 4) return "Neither";
                    int i = 0;
                    while(i < ch.length && (Character.isDigit(ch[i]) || (ch[i] >= 'a' && ch[i] <= 'f') || (ch[i] >= 'A' && ch[i] <= 'F'))){
                        i ++;
                    }
                    if(i != ch.length) 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.