首页 > 其他 > 详细

Leetcode Restore IP Addresses

时间:2014-06-25 22:41:09      阅读:438      评论:0      收藏:0      [点我收藏+]

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)

vector<string> restoreIpAddresses(string s) {
    vector<string> res;
    int n = s.length();
    if(s=="" || n > 12) return res;
    for(int i = 0 ; i < 3; ++ i){
        for(int j = i+1; j < min(i+4,n-2); ++ j){
            for(int k = j+1; k < n-1; ++ k){
                string a = s.substr(0,i+1);   int aa = stoi(a); 
                string b = s.substr(i+1,j-i); int bb = stoi(b);
                string c = s.substr(j+1,k-j); int cc = stoi(c);
                string d = s.substr(k+1);     int dd = stoi(d);
                if(aa >=0 && aa <= 255 && bb>=0 && bb <=255 && cc >= 0 && cc <=255 && dd >= 0 && dd<=255){
                    string str_a = to_string(aa), str_b = to_string(bb), str_c = to_string(cc), str_d = to_string(dd);
                    if(str_a.length() == a.length() && str_b.length() == b.length() && str_c.length() == c.length() && str_d.length() == d.length() ){
                    string str = str_a+"."+str_b+"."+str_c+"."+str_d;
                    res.push_back(str);
                    }
                }
            }
        }
    }
    return res;
}

 

Leetcode Restore IP Addresses,布布扣,bubuko.com

Leetcode Restore IP Addresses

原文:http://www.cnblogs.com/xiongqiangcs/p/3804541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!