枚举即可,但是小错误不断。
需要注意的是,有前导0的也属于不合法地址,不能被算进来。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
int n = s.length();
int i, j, k;
vector<string> tmp;
for (i = 1; i < 4; ++i) {
for (j = 1; j < 4; ++j) {
for (k = 1; k < 4; ++k) {
int p = n - i - j - k;
if (p < 0 || p > 3)
continue;
tmp.clear();
tmp.push_back(s.substr(0, i));
tmp.push_back(s.substr(i, j));
tmp.push_back(s.substr(i + j, k));
tmp.push_back(s.substr(i + j + k, p));
if (isValid(tmp)) {
string t;
for (int m = 0; m < tmp.size() - 1; ++m)
t += tmp[m] + ".";
t += tmp[3];
res.push_back(t);
}
}
}
}
return res;
}
bool isValid(vector<string> split) {
for (int i = 0; i < split.size(); ++i) {
if (split[i] == "")
return false;
if (atoi(split[i].c_str()) > 255 || atoi(split[i].c_str()) < 0)
return false;
if (split[i].size() > 1 && split[i][0] == '0')
return false;
}
return true;
}
};
http://oj.leetcode.com/problems/restore-ip-addresses/