视频讲解:https://www.bilibili.com/video/BV1XP4y1U73i/?vd_source=a935eaede74a204ec74fd041b917810c

这道题目可能上来看会有点懵,但是仔细捋捋总结下来就是这几个方面:
- 切割字符串,判断是否合法,合法就加逗点'.'继续遍历,不合法就直接break。
- 最后要判断是否有三个逗点,并且最后一个逗点后续的字符串合法,说明这个字符串合法,直接加入到result中即可。
- 在判断合法函数中,有以下几种情况1. 起始位置大于终止位置(很重要),false。2.起始位置是0并且终止位置不是0,false。3.最终计算结果大于255的, false。4.计算结果过程中发现不是数字的,false。
- 找到合法区间后,往后插入逗点,用insert( start, '.')函数加入逗点,回溯用earse(start)函数擦除逗点,因为insert了一位,在backtracking函数中起始位置由i+1变为i+2.
cpp
class Solution {
private:
vector<string> result;
void backtracking(string s, int startIndex, int pointSum)
{
//判断终止条件
if(pointSum == 3)
{
//并且最后的字符串要合法
if(isVaild(s, startIndex, s.size() -1))
{
result.push_back(s);
return;
}
return;
}
//单层搜索
for(int i = startIndex; i<s.size(); i++)
{
//判断合法性
if(isVaild(s, startIndex, i))
{
s.insert(s.begin() + i + 1, '.');
pointSum++;
//继续回溯,之前都是i+1,这次insert了一个'.',所以变成了i+2
backtracking(s, i + 2, pointSum);
//回溯
pointSum--;
s.erase(s.begin() + i + 1);
}
else break;
}
}
bool isVaild(string s, int startIndex, int endIndex)
{
if (startIndex > endIndex) {
return false;
}
//如果第一位为0,且收尾不相等直接false,即01情况
if(s[startIndex] == '0' && startIndex != endIndex)
{
return false;
}
int sum = 0;
int power = pow(10, endIndex - startIndex);
//根据位数计算综合
for(int i = startIndex; i < endIndex + 1; i++)
{
if (s[i] > '9' || s[i] < '0') // 遇到非数字字符不合法
{
return false;
}
//取单独一位
int single = s[i] - '0';
//计算sum
sum = sum + single * power;
//倍率缩小10倍
power = power / 10;
}
if(sum > 255)
{
return false;
}
return true;
}
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
if (s.size() < 4 || s.size() > 12) return result; // 算是剪枝了
backtracking(s, 0, 0);
return result;
}
};