Concise Java solution


  • 0
    M
    public class Solution {
    public String validIPAddress(String IP) {
        boolean is4 = IP.indexOf('.') > -1;
        char delim = is4 ? '.' : ':';
        int maxTokens = is4 ? 4 : 8;
        int maxTokenLen = is4 ? 3 : 4;
        int maxLen = maxTokens * maxTokenLen + maxTokens - 1;
        if (IP.length() > maxLen) return "Neither";
        
        
        int tokens = 1, chunk = 0, val = 0;
        for(int i = 0; i < IP.length(); i++) {
            char c = IP.charAt(i);
            if(c == delim) {
                tokens++;
                if(chunk == 0 || tokens > maxTokens) return "Neither";
                chunk = val = 0;
            } else if(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
                chunk++;
                val = val * 10 + c - '0';
                if(chunk > maxTokenLen ||
                    is4 && (c > '9' || val > 255 || chunk == 2 && IP.charAt(i-1) == '0')
                ) {
                    return "Neither";
                }
            } else {
                return "Neither";
            }
        }
        return tokens == maxTokens && chunk > 0 ? is4 ? "IPv4" : "IPv6" : "Neither";
    }
    

    }


Log in to reply
 

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