题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

#include <cstddef>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        // write code here
        // IPV4的规则是数字0-255, 01不合法
        // IPV6的规则是四位,每位0-9,a-f // :: 不合法
        // 首先检查是不是IPV4/IPV6
        if(IP.find('.')!=string::npos){
            // 说明是IPV4
            string subStr = IP;
            int index = 0;
            vector<string> strList;
            // 先将四个字符串取出来
            while(subStr.find('.')!=string::npos){
                int x = subStr.find('.');
                strList.push_back(subStr.substr(index, x-index));
                subStr = subStr.substr(x+1);
            }
            strList.push_back(subStr);
            
            for(string t : strList) cout<<t<<","; cout<<endl;
            if(strList.size()!=4){
                return "Neither";
            }
            for(int i=0; i<4;i++){
                string tmp = strList[i];
                if((tmp.size()!=1&&tmp[0]=='0')||tmp.size()==0){
                    return "Neither";
                }
                else{
                    for(char i : tmp){
                        if(!isdigit(i)){
                            return "Neither";
                        }
                    }
                    int num = stoi(tmp);
                    cout<<"num"<<num<<endl;
                    if(num<=255&&num>=0){
                        continue;
                    }
                    else{
                        return "Neither";
                    }
                }
            }
            return "IPv4";
        }
        
        if(IP.find(':')!=string::npos){
            string subStr = IP;
            int index = 0;
            vector<string> strList;
            // 先将四个字符串取出来
            while(subStr.find(':')!=string::npos){
                int x = subStr.find(':');
                strList.push_back(subStr.substr(index, x-index));
                subStr = subStr.substr(x+1);
            }
            strList.push_back(subStr);
            for(string t : strList) cout<<t; cout<<endl;
            if(strList.size()!=8){
                return "Neither";
            }
            for(int i=0; i<8;i++){
                string tmp = strList[i];
                if(tmp.size()==0||tmp.size()>4){
                    return "Neither";
                }
                for(char i : tmp){
                    if(!isxdigit(i)){
                        return "Neither";
                    }
                }
            }
            return "IPv6";
        }
        return "Neither";
    }
};

全部评论

相关推荐

08-07 11:41
安徽大学 Java
点赞 评论 收藏
分享
07-07 12:25
门头沟学院 Java
程序员牛肉:你这个智邮公司做的就是那个乐山市税务系统的服务吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务