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 my_atoi(string s)
{
int re = 0;
int k = 0;
while (k <s.length())
{
re = 10 * re + s[k] - '0';
k++;
}
return re;
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string>re;
vector< string>candi; vector<string>aa;
candi.push_back(s);
int k = 0;
while (true)
{
vector<string>newcandi;
k++;
for (int i = 0; i < candi.size(); i++)
{
if (k == 1)
{
for (int j = 1; j <= 3; j++)
{
string ss = candi[i];
if (ss.length() - j >= 3 && ss.length() - j <= 9)
{
int n = my_atoi(string(ss.begin(), ss.begin() + j));
if ( n <= 255)
{
if ((n == 0 && j == 1)||(n>0&&ss[0]!='0'))
{
ss.insert(ss.begin() + j, '.');
newcandi.push_back(ss);
}
}
}
}
}
else if (k == 2)
{
for (int j = 1; j <= 3; j++)
{
string ss = candi[i];
int pos = ss.rfind('.');
if (ss.length() - j-pos-1 >= 2 && ss.length() - j -pos-1<= 6)
{
int n = my_atoi(string(ss.begin() + pos + 1, ss.begin() + pos + 1 + j));
if (n <= 255 )
{
if ((n == 0 && j == 1) || (n > 0 && ss[pos + 1] != '0'))
{
ss.insert(ss.begin() + pos + j + 1, '.');
newcandi.push_back(ss);
}
}
}
}
}
else if (k == 3)
{
for (int j = 1; j <= 3; j++)
{
string ss = candi[i];
int pos = ss.rfind('.');
if (ss.length() - j -pos-1>= 1 && ss.length() - j-pos-1 <= 3)
{
int n = my_atoi(string(ss.begin() + pos + 1, ss.begin() + pos + 1 + j));
int n2 = my_atoi(string(ss.begin() + 1 + j + pos, ss.end()));
if (n <= 255 && n2 <= 255)
{
if (((n == 0 && j == 1) || (n > 0 && ss[pos + 1] != '0')) &&
((n2 == 0 && 1 + j + pos == ss.length() - 1) || (n2>0 && ss[1 + j + pos] != '0')))
{
ss.insert(ss.begin() + pos + j + 1, '.');
re.push_back(ss);
}
}
}
}
}
}
candi = newcandi;
if (k == 3)
return re;
}
}
};
accepted