1 题目
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
2 尝试解
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
string temp = "";
vector<string> result;
split(s,temp,result,4);
return result;
}
void split(string s,string&temp, vector<string>&result, int bytes){
if(s.size() > bytes*3 || s.size() < bytes) return;
if(s.size() == 0){
temp.pop_back();
result.push_back(temp);
return;
}
if(s[0] == '0'){ //every 0 must represent a byte by itself
temp = temp + "0.";
split(s.substr(1),temp,result,bytes-1);
return;
}
string split_one = temp + s.substr(0,1) + "."; //cut off the first char
split(s.substr(1),split_one,result,bytes-1);
if(s.size() > 1){
string split_two = temp + s.substr(0,2) + "."; //cut off the first two chars
split(s.substr(2),split_two,result,bytes-1);
}
if(s.size() > 2){
string split_three = temp + s.substr(0,3) + "."; //cut off the first three chars
if(atoi(s.substr(0,3).c_str()) <= 255){
split(s.substr(3),split_three,result,bytes-1);
}
}
}
};
3 标准解
class Solution {
public:
// c++ code
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
string ans;
for (int a=1; a<=3; a++)
for (int b=1; b<=3; b++)
for (int c=1; c<=3; c++)
for (int d=1; d<=3; d++)
if (a+b+c+d == s.length()) {
int A = stoi(s.substr(0, a));
int B = stoi(s.substr(a, b));
int C = stoi(s.substr(a+b, c));
int D = stoi(s.substr(a+b+c, d));
if (A<=255 && B<=255 && C<=255 && D<=255)
if ( (ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D)).length() == s.length()+3)
ret.push_back(ans);
}
return ret;
}
};