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:
bool valid(string s){
if(s.length() > 1 && s[0] == '0')
return false;
int n = 0;
for(int i = 0;i < s.length();i++){
n *= 10;
n += s[i] - '0';
}
return n <= 255;
}
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
for(int first = 1;first <= 3;first ++)
for(int second = 1;second + first <= s.length() - 2 && second <= 3;second ++)
for(int third = 1;third + second + first <= s.length() - 1 && third <= 3;third ++){
int fourth = s.length() - third - second - first;
if(fourth > 0 && fourth < 4){
string s1 = s.substr(0,first);
string s2 = s.substr(first,second);
string s3 = s.substr(first + second,third);
string s4 = s.substr(first + second + third,fourth);
if(valid(s1) && valid(s2) && valid(s3) && valid(s4)){
ret.push_back(s1 +'.'+ s2 +'.'+ s3 +'.'+ s4);
}
}
}
return ret;
}
};