Friday, April 10, 2015

93 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)
class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<int> ip;
        vector<string> res;
        help(s,ip,res,0);
        return res;
    }
    void help(string s, vector<int> & ip, vector<string> &res, int pos)
    {
        if (ip.size()==4 && pos == s.size())
        {
            string tmp;
            for (int i=0;i<ip.size();i++)
            {
                tmp+= to_string(ip[i])+".";
            }
            tmp.pop_back();
            res.push_back(tmp);
            return;
        }
        if (ip.size()==4 || pos>=s.size())
            return;
        for (int i=1;i<=3;i++)
        {
            string tmp = s.substr(pos,i);
            int val = stoi(tmp);
            if (isValid(tmp))
            {
                ip.push_back(val);
                help(s,ip,res,pos+i);
                ip.pop_back();
            }
        }
    }
    bool isValid(string s)
    {
        int i=0;
        if (s[0]=='0' && s.size()>1)
            return false;
        int val = stoi(s);
        if (val>=0 && val<=255)
            return true;
        return false;
    }

};

No comments:

Post a Comment