[LintCode] Restore IP Address 复原IP地址

 

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

Example

Given "25525511135", return

[
  "255.255.11.135",
  "255.255.111.35"
]

Order does not matter.

 

LeetCode上的原题,请参见我之前的博客Restore IP Addresses

 

解法一:

class Solution {
public:
    /**
     * @param s the IP string
     * @return All possible valid IP addresses
     */
    vector<string> restoreIpAddresses(string& s) {
        vector<string> res;
        helper(s, 4, "", res);
        return res;
    }
    void helper(string s, int k, string out, vector<string>& res) {
        if (k == 0) {
            if (s.empty()) res.push_back(out);
            return;
        } 
        for (int i = 1; i < 4; ++i) {
            if (s.size() < i) break;
            int val = stoi(s.substr(0, i));
            if (val > 255 || i != to_string(val).size()) continue;
            helper(s.substr(i), k - 1, out + s.substr(0, i) + (k == 1 ? "" : "."), res);
        }
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param s the IP string
     * @return All possible valid IP addresses
     */
    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 @ 2016-07-19 23:48  Grandyang  阅读(936)  评论(0编辑  收藏  举报
Fork me on GitHub