思路:ip地址有4段,深搜穷举每一个段。对Ip的每一段判断是否合法即可。
判断每个字段是不是合法就是判断该串转化为整数后是不是在0到255之间,当然还要特判该段是否是长度>1但是开头却是0的情况。比如192.025.1.27 第二个字段025长度为3大于1, 且以0开头,很明显不是合法的。
class Solution {
public:
vector<string>res;//记录结果
int a[4];//记录小数点的位置
vector<string> restoreIpAddresses(string s) {
int length = s.length();
if(length <= 0)
return res;
dfs(s, length, 0, length - 1, 0);
return res;
}
//start,end表示待摆放小数点的串的起始和终止位置
void dfs(string s, int length, int start, int end, int has){
if(has == 3){//三个小数点都已经摆了
string temp1 = "";
for(int i = 0; i <= a[0]; i++)//截取第一个字段
temp1 += s[i];
if(check(temp1, temp1.length() ) == false)//第一个字段都不合法了,结束吧
return ;
temp1 += '.';//加上点
string temp2= "";
for(int i = a[0] +1; i <=a[1]; i++){//截取第二个字段
//cout<<s[i];
temp2 += s[i];
}
if(check(temp2, temp2.length() ) == false)//第二个字段不合法
return ;
temp2 += '.';//加上点
string temp3 = "";
for(int i = a[1] +1; i <= a[2]; i++)//截取第三个字段
temp3 += s[i];
if(check(temp3, temp3.length() ) == false)//第三个字段不合法
return ;
//cout<<".";
temp3 += '.';//加上点
string temp4 = "";
for(int i = a[2] + 1; i < length; i++)//截取第四个字段
temp4 += s[i];
if(check(temp4, temp4.length() ) == false)//第四个字段不合法
return ;
string str = temp1 +temp2 +temp3+temp4;//四个字段都合法了,拼接
res.push_back (str);//存入
return ;
}
for(int p = start; p < end; p++){//枚举点可放的位置
a[has] = p;//第has+1个点放在s[p]的后面
has++;//把下个点
dfs(s, length, p + 1, end, has);
has--;//回溯
}
}
//检验串s是不是ip的合法字段
bool check(string s, int len){
if(len <= 0 ||len > 3)//位数超过3,不是合法的
return false;
if(len == 1)//只有1位肯定是合法的
return true;
if(s[0] == '0')//超过1位但是开头是0,比如025,明显不是合法的
return false;
long long sum = 0;
for(int i = 0; i < len; i++){//对字段转化为数字
sum = sum * 10 + s[i] - '0';
}
if(sum < 0 || sum > 255)//字段不在0到255 之内,不合法
return false;
return true;//合法
}
};