Tuesday, December 22, 2015

[LintCode] Restore IP Addresses Show result

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.

class Solution {
public:
    vector<string> helper(string s, int n) {
        int l = s.length();
        vector<string> res;
        
        if(3*n < l || n>l) {
            return res;
        }
        
        if(n == 1){
            if(l>1 && s[0] == '0') return res;
            if(stoi(s)<=255) {
                res.push_back(s);
            }
            return res;
        }
        
        for(int i=1;i<=3 && i<l;i++){
            string t = s.substr(0,i);
            if((i>1 && s[0] == '0') || 
                (i == 3 && stoi(t)>255)) break;
            vector<string> pp = helper(s.substr(i), n-1);
            for(auto e:pp) {
                res.push_back(t+"."+e);
            }
        }
        return res;
    }
    
    vector<string> restoreIpAddresses(string& s) {
        // Write your code here
        return helper(s, 4);
    }
};