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)
vector<string> restoreIpAddresses(string s) { vector<string> res; int n = s.length(); if(s=="" || n > 12) return res; for(int i = 0 ; i < 3; ++ i){ for(int j = i+1; j < min(i+4,n-2); ++ j){ for(int k = j+1; k < n-1; ++ k){ string a = s.substr(0,i+1); int aa = stoi(a); string b = s.substr(i+1,j-i); int bb = stoi(b); string c = s.substr(j+1,k-j); int cc = stoi(c); string d = s.substr(k+1); int dd = stoi(d); if(aa >=0 && aa <= 255 && bb>=0 && bb <=255 && cc >= 0 && cc <=255 && dd >= 0 && dd<=255){ string str_a = to_string(aa), str_b = to_string(bb), str_c = to_string(cc), str_d = to_string(dd); if(str_a.length() == a.length() && str_b.length() == b.length() && str_c.length() == c.length() && str_d.length() == d.length() ){ string str = str_a+"."+str_b+"."+str_c+"."+str_d; res.push_back(str); } } } } } return res; }