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 {
private:
void search(vector<string> &ans, string &s, int num, int idx, string t) {
string tmp = "";
if (num == 3 && idx + 1 <= s.size() - 1) {
if (s[idx + 1] == '0' && idx + 1 < s.size() - 1) {
return;
}
tmp = s.substr(idx + 1, s.size() - idx - 1);
if (atoi(tmp.c_str()) <= 255) {
ans.push_back(t + tmp);
}
}
else {
for (int i = idx + 1; i < s.size(); i++) {
tmp += s[i];
if (atoi(tmp.c_str()) <= 255) {
search(ans, s, num + 1, i, t + tmp + '.');
}
if (tmp[0] == '0') {
break;
}
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> ans;
search(ans, s, 0, -1, "");
return ans;
}
};
本文介绍了一个算法问题:如何将仅包含数字的字符串恢复为所有可能的有效IP地址组合。通过递归搜索的方法,文章详细展示了如何从给定字符串中找出所有合法的IP地址,并提供了具体的实现代码。
803

被折叠的 条评论
为什么被折叠?



