题解 | #验证IP地址#

验证IP地址

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


class Solution {
public:
    const string IPV4 = "IPv4";
    const string IPV6 = "IPv6";
    const string NEITHER = "Neither";
    const char IP4_SEP = '.';
    const char IP6_SEP = ':';
    /**
     * 验证IP地址
     * @param IP string字符串 一个IP地址字符串
     * @return string字符串
     */
    string solve(string IP) {
        // write code here
        if(contains_dot(IP) && isIPV4(IP)){
            return IPV4;
        }else if(contains_colon(IP) && isIPV6(IP)){
            return IPV6;
        }
        return NEITHER;
    }
    
    bool contains_dot(string IP){
        return IP.find(IP4_SEP) != string::npos;
    }
    
    bool contains_colon(string IP){
        return IP.find(IP6_SEP) != string::npos;
    }
    
    vector<string> split(string IP){ //实现split函数
        vector<string> ret;
        string tmp;
        for(size_t i = 0; i < IP.size(); i++){
            char c = IP[i];
            if(isalnum(c)){
                tmp.push_back(c);
                if(i == IP.size()-1){
                    ret.push_back(tmp);
                }
            }else{
                ret.push_back(tmp);
                tmp.clear();
            }
        }
        return ret;
    }
    
    bool isIPV4(string IP){
        vector<string> strs = split(IP);
        if(strs.size() != 4){
            return false;
        }
        for(auto str: strs){
            if(str.size() >= 2 && str[0] == '0'){
                return false;
            }
            for(auto c: str){
                if(!isdigit(c)){
                    return false;
                }
            }
            int num = atoi(str.c_str());
            if(num > 255 || num < 0){
                return false;
            }
        }
        return true;
    }
    
    bool isIPV6(string IP){
        vector<string> strs = split(IP);
        if(strs.size() != 8){
            return false;
        }
        for(auto str: strs){
            if(str.size() > 4){
                return false;
            }
            if(str == "0") continue;
            while(str[0] == '0'){  
                str = str.substr(1);
            }
            if(str.empty()){  //str.find_first_not_of('0') == string::npos
                return false;
            }
        }
        return true;
    }
};

全部评论

相关推荐

头像 头像
昨天 18:28
已编辑
Java
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务