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)
answer:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
if(s.length() < 4) return result;
for(int a = 1; a <= 3; a ++)
for(int b = 1; b <= 3; b ++)
for(int c = 1; c <= 3; c ++)
for(int d = 1; d <= 3; d ++){
if(a + b + c + d == s.length()){
int A = atoi((s.substr(0,a)).c_str());
int B = atoi(s.substr(a,b).c_str());
int C = atoi(s.substr(a + b,c).c_str());
int D = atoi(s.substr(a + b + c,d).c_str());
if(A <= 255 && B <= 255 && C <= 255 && D <= 255){
string temp = to_string(A) + "." + to_string(B) + "." + to_string(C) + "." + to_string(D);
if(temp.length() == s.length() + 3)
result.push_back(temp);
}
}
}
return result;
}
};