数字字符串转化成IP地址_牛客题霸_牛客网现在有一个只包含数字的字符串,将该字符串转化成IP地址的形式,返回所有可能的情况。。题目来自【牛客题霸】https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295
vector<string> restoreIpAddresses(string s) {
// write code here
int n = s.size();
vector<string> res;
for (int i = 1; i < 4 && i < n - 2; ++i)
{
for (int j = i + 1; j < i + 4 && j < n - 1; ++j)
{
for (int k = j + 1; k < j + 4 && k < n; ++k)
{
if (k < n - 3)
{
continue;
}
string a = s.substr(0, i);
string b = s.substr(i, j - i);
string c = s.substr(j, k - j);
string d = s.substr(k);
if (stoi(a) > 255 || stoi(b) > 255 || stoi(c) > 255 || stoi(d) > 255)
{
continue;
}
if ((a.size() > 1 && a.front() == '0') || (b.size() > 1 && b.front() == '0')
|| (c.size() > 1 && c.front() == '0') || (d.size() > 1 && d.front() == '0'))
{
continue;
}
res.push_back(a + '.' + b + '.' + c + '.' + d);
}
}
}
return res;
}