My Straightforward C++ Solution


  • 1
    G

    Valid IPv4 and IPv8 respectively:
    For IPv4:

    1. Should be exactly 4 parts splitted by '.', and the last char cannot be '.'
    2. The length of each part cannot be larger than 3, and if length is larger than 2, the first digit cannot be 0
    3. Each part can only be digit, and the value should between 0 and 255

    For IPv6:

    1. Should be exactly 8 parts splitted by ':', and the last char cannot be ':'
    2. The length of each part cannot be larger than 4
    3. Each part can only be digit, or letter 'a'-'f', 'A'-'F'
    class Solution {
    public:
        string validIPAddress(string IP) {
            istringstream is(IP);
            string t = "";
            int cnt = 0;
            if (IP.find(':') == string::npos) { // Check IPv4
                while (getline(is, t, '.')) {
                    ++cnt;
                    if (cnt > 4 || t.empty() || (t.size() > 1 && t[0] == '0') || t.size() > 3) return "Neither";
                    for (char c : t) {
                        if (c < '0' || c > '9') return "Neither";
                    }
                    int val = stoi(t);
                    if (val < 0 || val > 255) return "Neither";
                }
                return (cnt == 4 && IP.back() != '.') ? "IPv4" : "Neither";
            } else { // Check IPv6
                while (getline(is, t, ':')) {
                    ++cnt;
                    if (cnt > 8 || t.empty() || t.size() > 4) return "Neither";
                    for (char c : t) {
                        if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return "Neither";
                    }
                }
                return (cnt == 8 && IP.back() != ':') ? "IPv6" : "Neither";
            }
        }
    };

Log in to reply
 

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