您的位置:首页 > 其它

leetcode93 Restore IP Addresses

2016-01-06 16:09 260 查看
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:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
vector<int> cur(8,0);
dep(ans,s,0,cur,0);
return ans;
}

void dep(vector<string> &ans,string s,int ps,vector<int>&cur,int pc)
{
int len=s.length();
for(int i=1;i<=3;i++)
{
if(ps+i<=len)
{
if(judge(s.substr(ps,i)))
{
cur[pc]=ps;
cur[pc+1]=i;
if(ps+i==len&&pc==6)
addstr(ans,s,cur);
else if(ps+i!=len&&pc!=6)
dep(ans,s,ps+i,cur,pc+2);
}
}
}
}

bool judge(string str)
{
if(str.length()>1&&str[0]=='0')
return false;
int temp=atoi(str.c_str());
if(temp>=0&&temp<=255)
return true;
return false;
}

void addstr(vector<string> &ans,string s,vector<int>&cur)
{
string temp="";
temp+=s.substr(cur[0],cur[1]);
temp+=".";
temp+=s.substr(cur[2],cur[3]);
temp+=".";
temp+=s.substr(cur[4],cur[5]);
temp+=".";
temp+=s.substr(cur[6],cur[7]);
ans.push_back(temp);
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: