- 采用暴力搜索的办法,把每个string元素分组(1-3位一个组)都当做一个ip的地址元素进行匹配。最后判断ip是否符合要求。
#include
#include
#include
using namespace std;
vector vecip;
bool isValid(string strnum)
{
if (strnum > to_string(255))
{
return false;
}
return true;
}
void RestoreIPAddresses(string &str,int start,string ip,int lenP)
{
if (start >= str.size() && lenP != 4)
{
return;
}
if (start < str.size() - 1 && lenP == 4)
{
return;
}
if (start == str.size() && lenP == 4)
{
vecip.push_back(ip);
return;
}
if (start > str.size())
{
return;
}
int len = ip.size();
string ip1 = str.substr(start, 1);
if (len == 0)
{
ip = ip+ ip1;
}
else
{
ip = ip + ‘.’ + ip1;
}
RestoreIPAddresses(str, start + 1, ip, lenP+1);
ip = ip.substr(0, len);
string ip2 = str.substr(start, 2);
if (len == 0)
{
ip = ip + ip2;
}
else
{
ip = ip + '.' + ip2;
}
RestoreIPAddresses(str, start + 2, ip, lenP + 1);
ip = ip.substr(0, len);
string ip3 = str.substr(start, 3);
if (!isValid(ip3))
{
return;
}
if (len == 0)
{
ip = ip + ip3;
}
else
{
ip = ip + '.' + ip3;
}
RestoreIPAddresses(str, start + 3, ip, lenP + 1);
ip = ip.substr(0, len);
}
int main()
{
string str = “25525511135”;
string ip = “”;
RestoreIPAddresses(str, 0, ip, 0);
for (auto x : vecip)
{
cout << x << endl;
}
system("pause");
return 0;
}