题解 | #验证IP地址#

验证IP地址

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

#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    #include<sstream>
    #include<vector>
    #include<string>

    string ipv4Validation(vector<string> vecStr){
        int addNum = vecStr.size();
        if(addNum!=4){
            return "Neither";
        }
        for(string str:vecStr){
            if(str==""){return "Neither";}
            if(str[0]=='0'){return "Neither";}
            for(char ch : str){
                if(ch>='0'&&ch<='9'){continue;}
                else{return "Neither";}
            }
            int num = stoi(str);
            if(num>255){return "Neither";}
        }
        return "IPv4";
    }

    string ipv6Validation(vector<string> vecStr){
        int addNum = vecStr.size();
        if(addNum!=8){
            return "Neither";
        }
        for(string str:vecStr){
            if(str==""){return "Neither";}
            if(str.length()>4){return "Neither";}
            for(int i=0;i<str.length();i++){
                char ch = str[i];
                if(ch>='0'&&ch<='9'){continue;}
                else if(ch>='a'&&ch<='f'){continue;}
                else if(ch>='A'&&ch<='F'){continue;}
                else{return "Neither"; }
            }
        }
        
        return "IPv6";
    }



    string solve(string IP) {
        // write code here
        if(IP[IP.length()-1]=='.'||IP[IP.length()-1]==':'){return "Neither";}
        stringstream ssInput(IP);
        vector<string> vecStr;
        string instr;
        while(getline(ssInput,instr,'.')){
            vecStr.push_back(instr);
        }
        if(vecStr.size()==1){
            vecStr.clear();
            stringstream ssInput2(IP);
            while(getline(ssInput2,instr,':')){
                vecStr.push_back(instr);
            }
            return ipv6Validation(vecStr);
        }
        else{
            return ipv4Validation(vecStr); 
        }

    }
};

全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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