A simple, straightforward C++ solution


  • 0
    M
        string validIPAddress(string IP) {
            if(IP.length()<7) return "Neither";
            int flag=0;
            for(int i=0;i<5;i++)
            {
                if(IP[i]=='.') flag=1;
                if(IP[i]==':') flag=2;
            }
            vector<string> dict;
            if(flag==1)
            {
                dict=split(IP, '.'); 
                if(dict.size()!=4) return "Neither";
                for(int i=0;i<dict.size();i++)
                {
                    int num=0;
                    if(dict[i].length()!=1&&dict[i][0]=='0') return "Neither";
                    if(dict[i].length()>3||dict[i].size()<1) return "Neither";
                    for(int j=0;j<dict[i].size();j++)
                    {
                        if(dict[i][j]>'9'||dict[i][j]<'0') return "Neither";
                        num=num*10+(dict[i][j]-'0');
                    }
                    if(num>255||num<0) return "Neither";
                }
                return "IPv4";
            }
            else if (flag==2)
            {
                char s[]="0123456789abcdefABCDEF";
                set<char> temp(s, s+22);
                dict=split(IP, ':');
                if(dict.size()!=8) return "Neither";
                for(int i=0;i<dict.size();i++)
                {
                    if(dict[i].length()>4||dict[i].size()<1) return "Neither";
                    for(int j=0;j<dict[i].size();j++)
                    {
                        if(temp.find(dict[i][j])==temp.end()) return "Neither";
                    }
                }
                return "IPv6";
            }
            else return "Neither";
            return "Neither";
        }
        
        vector<string> split(string a, char b){
            vector<string> dict;
            int start=0, end=0;
            for(int i=0;i<a.length();i++)
            {
                if(a[i]==b) 
                {
                    dict.push_back(a.substr(start, end-start));
                    start=++end;
                    continue;
                }
                end++;
            }
            dict.push_back(a.substr(start, end-start));
            return dict;
        }

Log in to reply
 

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