class Solution {
public:
vector<string> path;
vector<string> res;
bool isIP(string& s, int startIndex, int endIndex)
{
//数字长度不正确
if (endIndex - startIndex + 1 > 3) return false;
string subString = s.substr(startIndex, endIndex - startIndex + 1);
int x = atoi(subString.c_str());
//数字范围不正确
if (x > 255)
return false;
//有前导0
if (subString.length() > 1 && subString[0] == '0')
return false;
return true;
}
void backtrack(string& s, int startIndex)
{
if (path.size() == 4 && startIndex >= s.length())
{
string temp = path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3];
res.push_back(temp);
return;
}
for (int i = startIndex; i < s.length(); i++)
{
if (isIP(s, startIndex, i))
{
path.push_back(s.substr(startIndex, i - startIndex + 1));
}
else
return;
backtrack(s, i + 1);
path.pop_back();
}
}
vector<string> restoreIpAddresses(string s) {
backtrack(s, 0);
return res;
}
};
LeetCode93.复原IP地址
最新推荐文章于 2024-08-17 08:45:02 发布