Clean JAVA solution


  • 0
    A
    public String validIPAddress(String IP) {
    	return isValidIP4(IP) ? "IPv4" : (isValidIP6(IP) ? "IPv6" : "Neither");
    }
    
    boolean isValidIP4(String str) {
    	if (countChar(str, '.') != 3) return false;
    	
    	String[] splits = str.split("\\.");
    	if (splits.length != 4) return false;
    	
    	for (String s : splits) {
    		if (s.isEmpty() || (s.charAt(0) == '0' && s.length() > 1) || s.length() > 3) return false;
    		for (char ch : s.toCharArray())
    			if ("0123456789".indexOf(ch) == -1) return false;
    		if (Integer.parseInt(s) > 255) return false;
    	}
    	return true;
    }
    
    boolean isValidIP6(String str) {
    	if (countChar(str, ':') != 7) return false;
    	
    	String[] splits = str.split(":");
    	if (splits.length != 8) return false;
    	
    	for (String s : splits) {
    		if (s.isEmpty() || s.length() > 4) return false;
    		for (char ch : s.toCharArray())
    			if ("0123456789abcdefABCDEF".indexOf(ch) == -1) return false;
    	}
    	return true;
    }
    
    int countChar(String str, char ch) {
    	int count = 0;
    	for (char c : str.toCharArray())
    		if (c == ch) count++;
    	return count;
    }

Log in to reply
 

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