[LeetCode] Restore IP Addresses

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

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

ip地址恢复

ip地址根据.分成4部分,每个部分都小于255.

编码判断即可

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        for (int a = 1; a < 4; ++a)
        {
            for (int b = 1; b < 4; ++b)
            {
                for (int c = 1; c < 4; ++c)
                {
                    for (int d = 1; d < 4; ++d)
                    {
                        if (a + b + c + d == s.size())
                        {
                            int A = stoi(s.substr(0, a));
                            int B = stoi(s.substr(a, b));
                            int C = stoi(s.substr(a+b, c));
                            int D = stoi(s.substr(a+b+c, d));
                            if (A <= 255 && B <= 255 && C <= 255 && D <= 255)
                            {
                                string t = to_string(A)+'.'+to_string(B)+'.'+to_string(C)+'.'+to_string(D);
                                if (t.size() == s.size()+3)
                                    res.push_back(t);
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
};

 

posted @ 2018-08-20 15:46  immjc  阅读(151)  评论(0编辑  收藏  举报