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

LeetCode93——Restore IP Addresses

时间:2015-04-20 14:53:39      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:leetcode   ip   string   


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, int index)
{
    vector<string> vip;
    if (index == 3) {
        if (s.size() == 0 || s.size() > 3 || (s.size() > 1 && s[0] == ‘0‘))
            return vip;
        int val = atoi(s.c_str());
        if (val >= 0 && val <= 255) {
            vip.push_back(s);
        }
        return vip;
    } else {
        for (int i = 1; i < 4 && i <= s.size(); i++) {
            string tmp = s.substr(0, i);
            if (i > 1 && s[0] == ‘0‘)
                continue;
            int val = atoi(tmp.c_str());
            if (val >= 0 && val <= 255) {
                vector<string> nextv = restoreIpAddresses(s.substr(i), index+1);
                for (int k = 0; k < nextv.size(); ++k) {
                    string ip(tmp);
                    ip.append(".").append(nextv[k]);
                    vip.push_back(ip);
                }
            }
        }
    }
    return vip;
}

vector<string> restoreIpAddresses(string s) {
    return restoreIpAddresses(s, 0);
}

LeetCode93——Restore IP Addresses

标签:leetcode   ip   string   

原文地址:http://blog.csdn.net/booirror/article/details/45150095

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