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)
Code:
<span style="font-size:14px;">class Solution {
public:
void helper(const string &s, int index, const int length, vector<string> &results, string result, int points) {
if (index == length) return;
if (points == 3) {
if (s[index] == '0') {
if (index == length-1) {
result += "0";
results.push_back(result);
}
return;
} else {
string temp = s.substr(index, length-index);
if (atoi(temp.c_str()) <= 255) {
result += temp;
results.push_back(result);
}
return;
}
} else {
if (s[index] == '0') {
helper(s, index+1, length, results, result+"0.", points+1);
} else {
for (int i = 1; i < 4 && index+i-1 < length; i++) {
string temp = s.substr(index, i);
if (atoi(temp.c_str()) <= 255) {
string tempResult = result+temp+".";
helper(s, index+i, length, results, tempResult, points+1);
} else
break;
}
}
return;
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> results;
helper(s, 0, s.size(), results, "", 0);
return results;
}
};</span>