leetcode 468 验证IP地址

验证IP地址

在这里插入图片描述

高刷题

class Solution {
    
    
public:
    bool cheakIP4(vector<string> &tmpIP4)
    {
    
    
        if(tmpIP4.size() != 4) return false;
        int tmp = 0;
        for(int i=0 ; i<tmpIP4.size() ; i++)
        {
    
    
            if(tmpIP4[i].size() > 1 && tmpIP4[i][0] == '0') return false;
            if(tmpIP4[i].size() == 0 || tmpIP4[i].size() > 3  )  return false;
            for(int j=0 ; j<tmpIP4[i].size() ; j++)
            {
    
    
                if( tmpIP4[i][j] >= '0' &&tmpIP4[i][j] <= '9')  {
    
    }
                else return false;
            }
            tmp = stoi(tmpIP4[i]);
            if(tmp < 0 || tmp > 255) return false;
        }
        return true;
    }
    bool cheakIP6(vector<string> &tmpIP6)
    {
    
    
        if(tmpIP6.size() != 8) return false;
        int tmp = 0; 
        
        for(int i=0 ; i<tmpIP6.size() ; i++)
        {
    
    
            if(tmpIP6[i].size() == 0 || tmpIP6[i].size() > 4)  return false;

            for(int j=0 ; j<tmpIP6[i].size() ; j++)
            {
    
    
                if( (tmpIP6[i][j] >= '0' &&tmpIP6[i][j] <= '9')
                    || (tmpIP6[i][j] >= 'a' &&tmpIP6[i][j] <= 'f')
                    || (tmpIP6[i][j] >= 'A' &&tmpIP6[i][j] <= 'F'))
                {
    
    }
                else return false;
            }
        }
        return true;
    }
    string validIPAddress(string queryIP) {
    
    
        
        string tmp;
        vector<string> tmpIP4;
        vector<string> tmpIP6;

        if(queryIP.find('.') != -1 )
        {
    
    
            for(int i=0 ; i <queryIP.size() ; i++)
            {
    
    
                if(queryIP[i] == '.')
                {
    
    
                    tmpIP4.push_back(tmp);
                    tmp.clear();
                    continue;
                } 
                tmp += queryIP[i];
            }
            tmpIP4.push_back(tmp);
            if(cheakIP4(tmpIP4) == true)  return "IPv4";
            else  return "Neither";
           
        }
        else if(queryIP.find(':') != -1 )
        {
    
    
            for(int i=0 ; i <queryIP.size() ; i++)
            {
    
    
                if(queryIP[i] == ':')
                {
    
    
                    tmpIP6.push_back(tmp);
                    tmp.clear();
                    continue;
                } 
                tmp += queryIP[i];
            }
            tmpIP6.push_back(tmp);
            if(cheakIP6(tmpIP6) == true)  return "IPv6";
            else  return "Neither";
            return "IPv6";
        }
        return "Neither";
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44814825/article/details/130003930