题意
给一个由数组组成的字符串,要求把这个字符串还原成IP。
结果返回所有合法的IP地址。
思路
回溯法。
注意前导0的判断。
代码
class Solution {
private:
vector<string> ans;
public:
int Judge(string s) {
if (s.length() > 1 && s[0] == '0') return -1;
int res = 0;
for (auto x : s) {
res *= 10;
res += x - '0';
}
return (res >= 0 && res <= 255) ? res : -1;
}
void dfs(string s, int step, int cnt, string t) {
if (step >= s.length() || cnt >= 4) {
if (step == s.length() && cnt == 4) {
ans.push_back(t);
}
return;
}
for (int i = step; i < min((int)s.length(), step + 3); i++) {
string x = s.substr(step, i - step + 1);
if (Judge(x) != -1) {
dfs(s, i + 1, cnt + 1, t + x + (cnt < 3 ? "." : ""));
}
}
}
vector<string> restoreIpAddresses(string s) {
ans.clear();
dfs(s, 0, 0, "");
return ans;
}
};