LeetCode : Restore IP Addresses

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)

需要注意atoi之前字符串的前几位是否为0


class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> res;
        string rcd;
        restore(res, rcd, s, 4);
        return res;
    }
    void restore(vector<string> & res, string &rcd, string s, int left){
        if(left == 0){
            if(s.size() == 0){
                rcd = rcd.substr(0,rcd.size() - 1);
                res.push_back(rcd);
            }
            return;
        }
        if(left * 3 < s.size()){return;}
        int num = 0;
        if(s.size() > 0){
            num = atoi(s.substr(0,1).c_str());
            if(num >=0 && num < 256){
                string temp = rcd + s.substr(0,1) + ".";
                restore(res, temp, s.substr(1), left - 1);
            }
        }
        if(s.size() > 1){
            num = atoi(s.substr(0,2).c_str());
            if(num >=10 && num < 256){
                string temp = rcd + s.substr(0,2) + ".";
                restore(res, temp, s.substr(2), left - 1);
            }
        }
        if(s.size() > 2){
            num = atoi(s.substr(0,3).c_str());
            if(num >=100 && num < 256){
                string temp = rcd + s.substr(0,3) + ".";
                restore(res, temp, s.substr(3), left - 1);
            }
        }
        return ;
    }
};


你可能感兴趣的:(LeetCode : Restore IP Addresses)