牛客题霸 [ 验证IP地址] C++题解/答案

牛客题霸 [ 验证IP地址] C++题解/答案

题目描述

编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址

IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。

IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。

然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 ( : : ) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。

说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。

题解:

其实就是按照题意模拟检验
注意特殊情况判断

代码:

class Solution {
public:
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        int pos1 = IP.find(".");
        int pos2 = IP.find(":");
        if((pos1 == IP.npos && pos2 != IP.npos) || (pos1 != IP.npos && pos2 == IP.npos))
        {
            string s = pos1 == IP.npos?":" : ".";
            int cnt = 0;
            int pos = IP.find(s);
            
            IP+=s;
            
            while(pos != IP.npos)
            {
                string temp = IP.substr(0,pos);
                if(s == ".")
                {
                    if(temp.length() == 0 || temp.length() >= 4 || cnt >= 4)return "Neither";
                    for(int i=0;i<temp.length();i++)
                    {
                        char c=temp[i];
                        if(!isdigit(c))return "Neither";
                    }
                    
                    int x = stoi(temp);
                    if(x >= 256 || x < 0)return "Neither";
                    if(to_string(x) != temp)return "Neither";
                }
                else
                {
                    if(temp.length() >= 5 || temp.length() == 0 || cnt >= 8)return "Neither";
                    for(int i=0;i<temp.length();i++)
                    {
                        char c=temp[i];
                        if(!isxdigit(c))return "Neither";
                    }
                }
                IP = IP.substr(pos + 1,IP.size());
                pos = IP.find(s);
                cnt++;
            }
            if(s == ".")
                return cnt == 4 ? "IPv4" : "Neither";
            else
                return cnt == 8 ? "IPv6" : "Neither";
        }
        return "Neither";
    }
};
posted @ 2020-12-01 22:47  回归梦想  阅读(272)  评论(0编辑  收藏  举报