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

[LeetCode]46. Restore IP Addresses复原IP地址

时间:2015-10-28 22:30:08      阅读:232      评论: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)

 

Subscribe to see which companies asked this question

 

解法1:暴力破解法。三层循环确定前面三个数字,最后剩下的所有作为第四个数字。实际每层循环最多执行三遍。循环中使用作为正确IP地址的条件进行剪枝。需要注意考虑各种边界条件。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        int n = s.size();
        string addr = "";
        vector<string> res;
        for (int i = 0; i < n - 3 && i < 3; ++i)
        {
            string fir(s.begin(), s.begin() + i + 1);
            if ((fir[0] != 0 || fir.size() == 1) && stoi(fir) <= 255)
            {
                for (int j = i + 1; j < n - 2 && j < i + 4; ++j)
                {
                    string sec(s.begin() + i + 1, s.begin() + j + 1);
                    if ((sec[0] != 0 || sec.size() == 1) && stoi(sec) <= 255)
                    {
                        for (int k = j + 1; k < n - 1 && k < j + 4; ++k)
                        {
                            string trd(s.begin() + j + 1, s.begin() + k + 1);
                            if ((trd[0] != 0 || trd.size() == 1) && stoi(trd) <= 255)
                            {
                                string fth(s.begin() + k + 1, s.end());
                                if ((fth[0] != 0 || fth.size() == 1) && fth.size() < 4 && stoi(fth) <= 255)
                                {
                                    addr += fir + . + sec + . + trd + . + fth;
                                    res.push_back(addr);
                                    addr.clear();
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
};

 

[LeetCode]46. Restore IP Addresses复原IP地址

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4918616.html

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