Easy to understand Java solution


  • 0
    W
    public class Solution {
        public String validIPAddress(String IP) {
            if (isIPv4(IP)) return "IPv4";
            if (isIPv6(IP)) return "IPv6";
            return "Neither";
        }
        
        private boolean isIPv4(String IP) {
            if (IP.length() > 0 && (IP.startsWith(".") || IP.charAt(IP.length()-1) == '.')) return false;
            
            String[] tokens = IP.split("\\.");
            if (tokens.length != 4) return false;
            
            for (String s : tokens) {
                if (s.length() == 0 || s.length() > 3) return false;
                if (s.length() > 1 && s.startsWith("0")) return false;
                
                for (char c : s.toCharArray()) {
                    if (!Character.isDigit(c)) return false;
                }
                
                int num = Integer.parseInt(s);
                if (num < 0 || num > 255) return false;
            }
            
            return true;
        }
        
        private boolean isIPv6(String IP) {
            if (IP.length() > 0 && (IP.startsWith(":") || IP.charAt(IP.length()-1) == ':')) return false;
            
            String[] tokens = IP.split(":");
            if (tokens.length != 8) return false;
            
            for (String s : tokens) {
                if (s.length() == 0 || s.length() > 4) return false;
                s = s.toLowerCase();
                
                for (char c : s.toCharArray()) {
                    if (!Character.isDigit(c) && (c < 'a' || c > 'f')) return false;
                }
            }
            
            return true;
        }
    }
    

Log in to reply
 

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