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)
vector<string> restoreIpAddresses(string s, int index)
{
vector<string> vip;
if (index == 3) {
if (s.size() == 0 || s.size() > 3 || (s.size() > 1 && s[0] == ‘0‘))
return vip;
int val = atoi(s.c_str());
if (val >= 0 && val <= 255) {
vip.push_back(s);
}
return vip;
} else {
for (int i = 1; i < 4 && i <= s.size(); i++) {
string tmp = s.substr(0, i);
if (i > 1 && s[0] == ‘0‘)
continue;
int val = atoi(tmp.c_str());
if (val >= 0 && val <= 255) {
vector<string> nextv = restoreIpAddresses(s.substr(i), index+1);
for (int k = 0; k < nextv.size(); ++k) {
string ip(tmp);
ip.append(".").append(nextv[k]);
vip.push_back(ip);
}
}
}
}
return vip;
}
vector<string> restoreIpAddresses(string s) {
return restoreIpAddresses(s, 0);
}
LeetCode93——Restore IP Addresses
原文地址:http://blog.csdn.net/booirror/article/details/45150095