Thinking process

Mistakes

String.split
  1. split string by dots should be => You need to escape the dot if you want to split on a _literal _dot
  2. split omit last empty string, but save the first empty string, after splitting the string
public class Solution {
    public String validIPAddress(String IP) {
        String[] strs = IP.split("\\.");
        if (strs.length == 4) {
            if (isValidIPv4(IP)) return "IPv4";
        } else if (strs.length == 1){
            if (isValidIPv6(IP)) return "IPv6";
        }

        return "Neither";
    }

    private boolean isValidIPv4(String IP) {
        int max = 255;
        int min = 0;

        if (IP.charAt(IP.length() - 1) == '.') return false; 

        String[] strings = IP.split("\\.");
        for (String s : strings) {
            if (s.length() < 1 || s.length() > 3 || (s.length() > 1 && s.charAt(0) == '0')) return false;

            for (int i = 0; i < s.length(); ++i) {
                if (!Character.isDigit(s.charAt(i))) {
                    return false;
                }
            }

            int value = Integer.valueOf(s);

            if (value > max || value < min) return false;

        }

        return true;
    }

    private boolean isValidIPv6(String IP) {
        String[] splitedIP = IP.split("\\:");

        if (splitedIP.length != 8 || IP.charAt(IP.length() - 1) == ':') return false;

        for (String s : splitedIP) {
            s = s.toLowerCase();

            if (s.length() == 0 || s.length() > 4) return false;

            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i); 

                if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
                    continue;
                } else {
                    return false;
                }
            }


        }

        return true;
    }
}

results matching ""

    No results matching ""