Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

class Solution {
private:
    vector< string> result;
    unordered_set< string> ipset;
public:
    vector< string> restoreIpAddresses( string s) 
    {
        result.clear();
         int len=s.length();
         if(len< 4return result;
         for( int i1= 0;i1<=len- 4 && i1+ 1<= 3;i1++)
             for( int i2=i1+ 1;i2<=len- 3 && i2-i1<= 3;i2++)
                 for( int i3=i2+ 1;i3<=len- 2 && i3-i2<= 3;i3++)
                 if(len-i3- 1<= 3)
                {
                     int len1=i1+ 1;
                     int len2=i2-i1;
                     int len3=i3-i2;
                     int len4=len-i3- 1;
                     int add1=atoi(s.substr( 0,len1).c_str());
                     int add2=atoi(s.substr(i1+ 1,len2).c_str());
                     int add3=atoi(s.substr(i2+ 1,len3).c_str());
                     int add4=atoi(s.substr(i3+ 1,len4).c_str());
                     string s1=getstring(add1);
                     string s2=getstring(add2);
                     string s3=getstring(add3);
                     string s4=getstring(add4);
                     if(add1>= 0 && add1<= 255 && add2>= 0 && add2<= 255
                    && add3>= 0 && add3<= 255 && add4>= 0 && add4<= 255)
                    {
                         string ip=s1+ " . "+s2+ " . "+s3+ " . "+s4;
                         if(ip.length()== 3+len && ipset.find(ip)==ipset.end())
                        {
                            result.push_back(ip);
                            ipset.insert(ip);
                        }
                    }
                }
         return result;
    }
     string getstring (  const  int n )
    {
        std::stringstream newstr;
        newstr<<n;
         return newstr.str();
    }
};  

你可能感兴趣的:(store)