A simple Java solution


  • 0
    Y
    public class Solution {
        public String validIPAddress(String IP) {
            if (IP.split("\\.", -1).length == 4) {
                for (String s : IP.split("\\.", -1))
                    if (validIPv4(s) == false)
                        return new String("Neither");
    
                return new String("IPv4");
            } else if (IP.split("\\:", -1).length == 8) {
                for (String s : IP.split(":", -1))
                    if (!(validIPv6(s))) 
                        return new String("Neither");
    
                return new String("IPv6");
            } else {
                return new String("Neither");
            }
        }
        
        private boolean validIPv4(String s) {
            if (s == null || s.length() == 0 || s.length() > 3 || (s.length() > 1 && s.charAt(0) == '0'))
                return false;
                
            for (int i = 0; i < s.length(); i++)
                if (s.charAt(i) > '9' || s.charAt(i) < '0')
                    return false;
            
            if (Integer.valueOf(s) < 0 || Integer.valueOf(s) > 255)
                return false;
                
            return true;
        }
        
        private boolean validIPv6(String s) {
            if (s == null || s.length() == 0 || s.length() > 4)
                return false;
                
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if ((c > '9' || c < '0') && (c > 'f' || c < 'a') && (c > 'F' || c < 'A'))
                    return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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