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 {
int MIN(int a, int b)
{
if (a > b)
return b;
return a;
}
int str2int(string &str) {
int size = str.size();
int retVal = 0;
for (int i = 0; i < size; i++)
{
retVal = retVal*10+(str[i]-'0');
}
return retVal;
}
bool isValidNum(int num)
{
if (num > 255)
return false;
return true;
}
void foo(string remainString, int remainNum, string &curString, vector<string> &retStrings)
{
if ((remainNum == 0) && (remainString.size() == 0))
{
retStrings.push_back(curString);
return;
}
if ((remainString.size() > remainNum*3) || (remainString.size() < remainNum))
return;
if (remainNum > 0 && remainNum < 4)
curString += ".";
int maxTryNum = MIN(3, remainString.size());
for (int tryNum = maxTryNum; tryNum >= 1; tryNum--)
{
string tryString = remainString.substr(0, tryNum);
if (tryNum > 1 && tryString[0] == '0')
continue;
if (tryNum == 3 && !isValidNum(str2int(tryString)))
continue;
curString += tryString;
foo(remainString.substr(tryNum, remainString.size()-tryNum), remainNum-1, curString, retStrings);
curString = curString.substr(0, curString.size()-tryNum);
}
if (remainNum > 0 && remainNum < 4)
curString = curString.substr(0, curString.size()-1);
}
public:
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> retStrings;
string curString;
foo(s, 4, curString, retStrings);
return retStrings;
}
};