Restore IP Addresses

2014-11-24 01:33:01 · 作者: · 浏览: 1

题目:


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)

代码如下:

bool iscorrect(string s)
{
if(s.length()==2)
{
if(s[0]=='0')return false;
}
if(s.length()==3)
{
int tmp=(s[0]-'0')*100+(s[1]-'0')*10+(s[2]-'0');
if(tmp<100||tmp>255)return false;
}
return true;
}
bool istrue(string a,string b,string c,string d)
{
if(a.length()>3||b.length()>3||c.length()>3||d.length()>3)
{
return false;
}
if(iscorrect(a)&&iscorrect(b)&&iscorrect(c)&&iscorrect(d))
{
return true;
}
else
{
return false;
}
}
vector restoreIpAddresses(string s) {
int n=s.length();
vector result;
if(n<4||n>12)return result;
int i=0;
for(int j=1;j {
for(int k=j+1;k {
for(int t=k+1;t {
string a=s.substr(i,j-i),b=s.substr(j,k-j),c=s.substr(k,t-k),d=s.substr(t,n-k);
if(istrue(a,b,c,d))
{
string tmp;
tmp=a+"."+b+"."+c+"."+d;
result.push_back(tmp);
}
}
}
}
return result;