Leetcode 468 Solution

This article provides solution to leetcode question 468 (validate-ip-address)

https://leetcode.com/problems/validate-ip-address

Solution

class Solution {
public:
    vector<string> split(const string& str, char splitter)
    {
        vector<string> tokens;

        int last_start = 0;
        for (int i = 0; i < str.size(); i++)
        {
            if (str[i] == splitter)
            {
                tokens.push_back(str.substr(last_start, i - last_start));
                last_start = i + 1;
            }
        }

        tokens.push_back(str.substr(last_start, str.size() - last_start));
        return tokens;
    }

    string validIPAddress(string IP)
    {
        if (IP.find('.') != string::npos)
        {
            auto tokens = split(IP, '.');

            if (tokens.size() != 4)
                return "Neither";

            vector<int> nums(4);

            for (int i = 0; i < 4; i++)
            {
                nums[i] = atoi(tokens[i].c_str());

                if (to_string(nums[i]) != tokens[i])
                    return "Neither";

                if (nums[i] < 0 || nums[i] > 255)
                    return "Neither";
            }

            return "IPv4";
        }
        else if (IP.find(':') != string::npos)
        {
            auto tokens = split(IP, ':');

            if (tokens.size() != 8)
                return "Neither";

            for (int i = 0; i < tokens.size(); i++)
            {
                auto token = tokens[i];

                if (token.size() > 4 || token.size() == 0)
                    return "Neither";

                for (int j = 0; j < token.size(); j++)
                {
                    if (('0' <= token[j] && token[j] <= '9')
                        || ('a' <= token[j] && token[j] <= 'f')
                        || ('A' <= token[j] && token[j] <= 'F'))
                        continue;

                    return "Neither";
                }
            }

            return "IPv6";
        }

        return "Neither";
    }
};