My short 0ms C++ solution


  • 1
    S
    class Solution {
    public:
        string validIPAddress(string IP) {
            string ans;
            int n=IP.size();
            if (n==0) return "Neither";
            bool v4=false;
            bool v6=false;
            int firstdot=IP.find_first_of('.');
            int firstcol=IP.find_first_of(":");
            if (firstdot>0)  v4=validateIPv4(IP); 
            if (firstcol>0)  v6=validateIPv6(IP);
            if (!v4&&!v6)  ans="Neither";
            else if (v4)   ans="IPv4";
            else if (v6)   ans="IPv6";
            return ans;
        }
        bool validateIPv4(string IP)
        {
             stringstream ss(IP);
             string buf;
             int count=0;
             if (!isdigit(IP.back()))
                return false;
             while (getline(ss,buf,'.'))
             {
                 if ((buf[0]=='0' && buf.size()>1)||buf.size()>3) return false;
                 for (int i=0; i<buf.size(); i++)
                    if (!isdigit(buf[i]))
                      return false;
                 int dig=stoi(buf);
                 if (dig<0 || dig>255)
                   return false;
                 count++;
             }
             return (count==4);
        }
        bool validateIPv6(string IP)
        {
            char back=IP.back();
            if (!isdigit(back)&&(back<'a'||back>'f'))
                return false;
             stringstream ss(IP);
             string buf;
             int count=0;
             while (getline(ss,buf,':'))
             {
                if (buf.empty()||buf.size()>4) return false;
                for (int i=0; i<buf.size(); i++)
                {
                  char c=tolower(buf[i]);
                  if (!isdigit(c)&&(c<'a'||c>'f'))
                    return false;
                }
                count++;
             }
             return (count==8);
        }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.