Leetcode 468.验证IP

目录

代码效果 

思路


代码效果 

 

思路

  1. 先根据是否包含三个 '.' 符和七个 ':' 符初步筛选符合要求的IPv4和IPv6地址
  2. 将IP地址字符串按照分割符进行分割
  3. 分别判断每段分割数据是否符合要求
class Solution {
public:
    //判断IPv4各段数据是否正确
    bool validateInt(string s){
        int len=s.length();
        int i;
        int num;
        
        if(s=="")    //判断是否为空
            return false;
        if(len!=1&&s[0]=='0')    //判断是否包含前导0,例如 "001"
            return false;
        for(i=0;i<len;i++){    //判断是否包含非法字符
            if(s[i]<'0'||s[i]>'9')
                return false;
        }
        num=atoi(s.c_str());    //string类型转为int类型
        if(num<0||num>255)    //判断是否在[0,255]内
            return false;
        return true;
    }

    //判断IPv6各段数据是否正确
    bool validateIPv6(string s){
        int len=s.length();
        int i;
        int num;
        if(len==0||len>4)    //判断IPv6各段长度是否在[1,4]内
            return false;
        for(i=0;i<len;i++){    //判断是否包含非法字符
            if(s[i]>='0'&&s[i]<='9'||s[i]>='a'&&s[i]<='f'||s[i]>='A'&&s[i]<='F')
                continue;
            else 
                return false;
        }
        return true;
    }
    string validIPAddress(string queryIP) {
        vector<string> s;
        int i=0;
        if(count(queryIP.begin(),queryIP.end(),'.')==3){    //queryIP中包含三个'.',IPv4地址的第一步筛选
            //以'.'为界分割字符串,分割出来的子串存在 vector<string>中
            int pos=0;
            int end=queryIP.find('.');
            while(end!=-1){
                s.push_back(queryIP.substr(pos,end-pos));
                pos=end+1;
                end=queryIP.find('.',pos);
            }
            s.push_back(queryIP.substr(pos,queryIP.length()-pos));

            //判断各数据段是否符合要求
            for(i=0;i<4;i++){
                if(!validateIPv4(s[i]))
                    return "Neither";
            }
            return "IPv4";
        }else if(count(queryIP.begin(),queryIP.end(),':')==7){    //queryIP是否包含7个':'
            //以':'为界分割字符串,分割出来的子串存在 vector<string>中
            int pos=0;
            int end=queryIP.find(':');
            while(end!=-1){
                s.push_back(queryIP.substr(pos,end-pos));
                pos=end+1;
                end=queryIP.find(':',pos);
            }
            s.push_back(queryIP.substr(pos,queryIP.length()-pos));

            //判断各数据段是否符合要求
            for(i=0;i<8;i++){
                if(!validateIPv6(s[i]))
                    return "Neither";
            }
            return "IPv6";  
        }else {
            return "Neither";
        }
    }
};

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值