题目描述
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given"25525511135",
return["255.255.11.135", "255.255.111.35"]. (Order does not matter)
//看来没有更好的解法
class Solution {
public:
int sitoi(string s)
{
int sum=0;
for(int i=0;i<s.size();++i)
sum=sum*10+s[i]-'0';
return sum;
}
void IpAddress(string str,int cnt,string obj,vector<string>&ans)
{
if(str.size()<=0) return ;
if(cnt==4)
{
if(str.size()<=3&&sitoi(str)<=255)
{
if(str.size()==1||str.size()!=1&&str[0]!='0')
{
obj+=str;
ans.push_back(obj);
}
}
return ;
}
if(str.size()>3)
{
IpAddress(str.substr(1,str.size()),cnt+1,obj+str.substr(0,1)+'.',ans);
if(str[0]!='0') IpAddress(str.substr(2,str.size()),cnt+1,obj+str.substr(0,2)+'.',ans);
if(str[0]-'2'<=0&&str[0]!='0'&&sitoi(str.substr(0,3))<=255) IpAddress(str.substr(3,str.size()),cnt+1,obj+str.substr(0,3)+'.',ans);
}
else if(str.size()>2)
{
IpAddress(str.substr(1,str.size()),cnt+1,obj+str.substr(0,1)+'.',ans);
if(str[0]!='0') IpAddress(str.substr(2,str.size()),cnt+1,obj+str.substr(0,2)+'.',ans);
}
else if(str.size()>1)
IpAddress(str.substr(1,str.size()),cnt+1,obj+str.substr(0,1)+'.',ans);
}
vector<string> restoreIpAddresses(string s) {
vector<string>res;
string temp="";
IpAddress(s,1,temp,res);
return res;
}
};