tricky stuff with java.String.split()


  • 0
    2
    1. IP.split(".") is not gonna work.
    2. If you use IP.split("\."), from the doc "Trailing empty strings are therefore not included in the resulting array." So strings like "1.2.3.4..." will pass.
    public class Solution {
        public String validIPAddress(String IP) {
            if (IP.contains(".")) {
                String[] token = IP.split("\\.", 4);
                if (token.length != 4) {
                    return "Neither";
                }
                for (String s : token) {
                    if (s.length() == 0 || s.length() > 3) {
                        return "Neither";
                    }
                    if (s.length() > 1 && s.charAt(0) == '0') {
                        return "Neither";
                    }
                    for (int i = 0; i < s.length(); i++) {
                        if (!isDecDigit(s.charAt(i))) {
                            return "Neither";
                        }
                    }
                    int val = Integer.parseInt(s);
                    if (val < 0 || val > 255) {
                        return "Neither";
                    }
                }
                return "IPv4";
            }
            if (IP.contains(":")) {
                String[] token = IP.split("\\:", 8);
                if (token.length != 8) {
                    return "Neither";
                }
                for (String s : token) {
                    if (s.length() == 0 || s.length() > 4) {
                        return "Neither";
                    }
                    for (int i = 0; i < s.length(); i++) {
                        if (!isHexDigit(s.charAt(i))) {
                            return "Neither";
                        }
                    }
                }
                return "IPv6";
            }
            return "Neither";
        }
        private boolean isDecDigit(char c) {
            return c >= '0' && c <= '9';
        }
        private boolean isHexDigit(char c) {
            return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
        }
    }
    

Log in to reply
 

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