[LeetCode] 086: Restore IP Addresses

来源:互联网 发布:怎么上淘宝的每日好店 编辑:程序博客网 时间:2024/06/16 00:02
[Problem]

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)


[Analysis]
IP的每部分,除非是0,否则不能有前导0.

[Solution]
class Solution {
public:
/**
* is the str a part of a valid IP address
*/
bool isValid(string str){
// invalid
if(str.size() == 0 || str.size() > 3)return false;
if(str.size() > 1 && str[0] == '0')return false;

// generate the value of the str
int res = 0;
for(int i = 0; i < str.size(); ++i){
if(str[i] >= '0' && str[i] <= '9'){
res = res*10 + (str[i] - '0');
}
else{
return false;
}
}

// valid
if(res >= 0 && res <= 255)return true;
// invalid
return false;
}
/**
* restore Ip addresses with 'part' parts
*/
vector<string> restoreIpAddresses(string s, int part){
vector<string> res;

// invalid
if(s.size() == 0 || part < 1 || part > 4)return res;

// the last part
if(1 == part){
if(isValid(s)){
res.push_back(s);
}
}
else{
for(int len = 1; len <= min(3, int(s.size())); ++len){
string head = s.substr(0, len);
if(!isValid(head))continue;

// valid
vector<string> nextRes = restoreIpAddresses(s.substr(len, s.size()-len), part-1);
for(int i = 0; i < nextRes.size(); ++i){
res.push_back(head + "." + nextRes[i]);
}
}
}
return res;
}
/**
* restore Ip addresses
*/
vector<string> restoreIpAddresses(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return restoreIpAddresses(s, 4);
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击