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> ips=restoreIpAddresses(s,4);//常规ip表示法有4个ip段
return ips;
}
private:
vector<string> restoreIpAddresses(string s,int restSegment) {
vector<string> ips;
if(restSegment == 1){//最后一个ip段
if(isIpSegment(s)){
ips.push_back(s);
}
return ips;
}
int len = s.size();
for(int i=0;i<3 ;++i){//每个ip段最多3位
string first = s.substr(0,i+1);
if(isIpSegment(first)){
if(i+1 < len){
vector<string> rest = restoreIpAddresses(s.substr(i+1,len-i-1),restSegment-1);
for(int j=0;j<rest.size();++j){
ips.push_back(first+"."+rest[j]);
}
}
}
}
return ips;
}
bool isIpSegment(string s){//判断一个段是否满足ip地址的要求
int intValue=atoi(s.c_str());
bool inScole = (intValue>=0 && intValue<=255);
if(!inScole) return false;
int len = s.size();
if(len>1 && s[0]=='0') return false;
return true;
}
};