Thursday, October 17, 2013

Restore IP Addresses [Leetcode]

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)

Solution: backtracking; each IP address is composed of 4 numbers separated by '.'; each non-zero number is not supposed to start with '0' in order to eliminate duplicates; each number is in the range of [0, 255].

class Solution {
public:
    void restoreIpAddressesHelper(vector<string>& ret, int depth, int cur, int n, string s, string r){
        if(depth==3){
            if(n-cur>3 || (cur!=n-1 && s[cur]=='0'))
                return;
            if(stoi(s.substr(cur, n-cur))<=255){
                r+=s.substr(cur, n-cur);
                ret.push_back(r);
            }
            return;
        }
        for(int i=1; i<=3; i++){
            if(cur+i<n && (i==1 || s[cur]!='0') && stoi(s.substr(cur, i))<=255)
                restoreIpAddressesHelper(ret, depth+1, cur+i, n, s, r+s.substr(cur, i)+".");
        }
    }
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> ret;
        int n = s.size();
        if(n<=3) return ret;
        string r;
        restoreIpAddressesHelper(ret, 0, 0, n, s, r);
        return ret;
    }
};

No comments:

Post a Comment