Short O(N) JAVA solution


  • 0

    The N of time complexity O(N) refers to the length of String IP. We should pay attention to several points when checking the IP in this question.

    IPv4:
    IPv4 should not contain ":" and should not begin/end with ".". It should contain 3 "."s which separate the IP into 4 parts, each part should be a number within [0, 255] (Note that a number like "04" is not allowed).

    IPv6:
    IPv6 should not contain "." and should not begin/end with ":". It should contain 7 ":"s which separate the IP into 8 parts, each part should consists of numbers within [0, 9] and letters within [a, f] and [A, F], the maximum length of each part is 4.

    public class Solution {
        public String validIPAddress(String IP) {
            return IP.contains(".") ? v4Check(IP) : IP.contains(":") ? v6Check(IP) : "Neither";
        }
        
        private String v4Check(String IP) {
            if (IP.charAt(0) == '.' || IP.charAt(IP.length()-1) == '.') return "Neither";
            String[] sArray = IP.split("\\.");
            if (sArray.length != 4) return "Neither";
            for (String s : sArray) {
                if (s.length() > 3 || (s.charAt(0) == '0' && s.length() > 1)) return "Neither";
                for (int i = 0; i < s.length(); ++i)
                    if (!Character.isDigit(s.charAt(i))) return "Neither";
                int tmp = Integer.parseInt(s);
                if (tmp < 0 || tmp > 255) return "Neither";
            }
            return "IPv4";
        }
        
        private String v6Check(String IP) {
            if (IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == ':') return "Neither";
            String v6Reg = "0123456789abcdefABCDEF";
            String[] sArray = IP.split(":");
            if (sArray.length != 8) return "Neither";
            for (String s : sArray) {
                if (s.length() > 4 || s.length() < 1) return "Neither";
                for (int i = 0; i < s.length(); ++i) {
                    if (!v6Reg.contains(s.charAt(i)+"")) return "Neither";
                }
            }
            return "IPv6";
        }
    }
    

Log in to reply
 

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