码迷,mamicode.com
首页 > 其他好文 > 详细

Restore IP Addresses

时间:2014-06-03 14:06:24      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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)

bubuko.com,布布扣
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();
    }
}; 
bubuko.com,布布扣

Restore IP Addresses,布布扣,bubuko.com

Restore IP Addresses

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!