leetcode 93 复原IP地址

2023-02-28,,

IP地址,分成四段,每段是0-255,按照每段的长度分别为1,2,3下一段长度分别1,2,3再下一段。。。。。。进行递归遍历,能满足条件的假如res中。比较难想到的就是假如有一段是三位的010是不符合要求的。这点一开始没想到,改成首尾不是0的才执行结果又漏掉了单个0的IP地址,比如0.0.0.0.。除了这两点之外剩下的代码还算好想。

#include<bits/stdc++.h>
using namespace std;
class Solution {
private:
void getIP(string s,int x,int y,vector<string>&res,string &ans,int sum)//[x,x+y-1]前闭后闭从string s的第x位开始获取y位数字组成IP地址。
{
int n;
n = s.size();
int i;
if (x + y -> n - ||sum>)
return;
if (( - sum) * + x + y- < n - )//如果剩下的几次都取3个数字都取不完所有元素,那么返回。
return;
if (y == )
{
if ( * (s[x] - '') + * (s[x + ] - '') + (s[x + ] - '') > )
return;
}
if (s[x] - '' == &&y!=)
return;
for (i = x; i <= x + y-; i++)
{
ans.push_back(s[i]);
if (i == x + y-&&sum!=)
ans.push_back('.');
}
if (x + y- == n - &&sum==)//第三次取完了所有string s里面的元素,保存结果.
{
res.push_back(ans);
for (i = ; i < y; i++)//回溯
{
ans.pop_back();
}
return;
}
// if(y+2<=n-1)
getIP(s,x+y , ,res,ans,sum+);
// if(y+3<=n-1)
getIP(s, x+y , ,res,ans,sum+);
// if(y+4<=n-1)
getIP(s, x+y, ,res,ans,sum+);
ans.pop_back();
for (i = ; i < y; i++)
ans.pop_back();
return;
}
public:
vector<string> restoreIpAddresses(string s) {
int n = s.size();
vector<string>res;
string ans;
ans.clear();
getIP(s, , , res, ans, );
ans.clear();
getIP(s, , , res, ans, );
ans.clear();
getIP(s, , , res, ans, );
return res;
}
};

leetcode 93 复原IP地址的相关教程结束。

《leetcode 93 复原IP地址.doc》

下载本文的Word格式文档,以方便收藏与打印。