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]
(1)合法的IP所有数字的长度不超过12,对于超过12的字符串,直接判为非法;
(2)对于长度小于等于12的字符串,枚举每一位的长度,每一位的长度为1~3;
(3)每一位除了单独为0外,不能以0开头;
[Solution]
class Solution {
public:
// is s valid for a part of IP
bool valid(string s){
// empty string
if(s.length() == 0){
return false;
}
else if(s.length() > 1 && s[0] == '0'){
return false;
}
// non-empty string
int val = 0;
for(int i = 0; i < s.length(); ++i){
val = val * 10 + (s[i] - '0');
}
// valid
if(val <= 255){
return true;
}
else{
return false;
}
}
// restore IP addresses
vector<string> restoreIpAddresses(string s, int nth){
vector<string> res;
// invalid string
if(s.length() > (5 - nth) * 3){
return res;
}
// the last value
if(nth == 4){
if(valid(s)){
res.push_back(s);
}
}
else{
// the length of each part should between 1 and 3
for(int i = 1; i <= 3 && i <= s.length(); ++i){
string str = s.substr(0, i);
// invalid
if(!valid(str))continue;
// search
vector<string> r = restoreIpAddresses(s.substr(i, s.length()-i), nth+1);
for(int j = 0; j < r.size(); ++j){
res.push_back(str + "." + r[j]);
}
}
}
return res;
}
// restore IP addresses
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return restoreIpAddresses(s, 1);
}
};
说明:版权所有,转载请注明出处。 Coder007的博客