leetcode--93. 复原IP地址

题目:93. 复原IP地址

链接:https://leetcode-cn.com/problems/restore-ip-addresses/

这个题暴力能过,因为给的字符串比较短嘛

C++:

class Solution {
public:
    bool checkNum(const string &num) {
        return !((num[0] == '0' && num.length() > 1) || (atoi(num.c_str()) > 255));
    }

    vector restoreIpAddresses(string s) {
        vector ret;
        if (s.length() < 4 || s.length() > 12) {
            return ret;
        }
        auto len = s.length();
        for (auto i = 1; i < len; i++) {
            for (auto j = i + 1; j < len; j++) {
                for (auto k = j + 1; k < len; k++) {
                    if (i != j && j != k) {
                        string tmp1=s.substr(0, i), tmp2=s.substr(i, j - i),
                        tmp3=s.substr(j, k - j), tmp4=s.substr(k, len - k);
                        if (checkNum(tmp1) && checkNum(tmp2) && checkNum(tmp3) && checkNum(tmp4)) {
                            ret.push_back(tmp1 + "." + tmp2 + "." + tmp3 + "." + tmp4);
                        }
                    }
                }
            }
        }
        return ret;
//        for (auto item:ret) {
//            cout << item << endl;
//        }
    }
};

如果想到其他解法的话再贴在下面

---------------------------------------------

你可能感兴趣的:(leetcode)