Restore IP Addresses

本文探讨了如何将一串仅包含数字的字符串恢复为所有可能的有效IP地址组合。例如,对于输入'25525511135',程序应返回['255.255.11.135', '255.255.111.35']等有效IP地址。

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)

#include <iostream> #include <vector> #include <string> using namespace std; // 手动判断子串是否合法,并转为整数(避免 stoi 和 substr) bool isValidPart(const string& s, int start, int len) { if (len == 0 || len > 3) return false; if (len > 1 && s[start] == '0') return false; // 前导零非法 int num = 0; for (int i = 0; i < len; ++i) { char c = s[start + i]; if (c < '0' || c > '9') return false; // 非数字字符(其实题目保证只有数字) num = num * 10 + (c - '0'); } return num <= 255; } // 获取所有有效 IP 地址(无 substr,纯索引操作) vector<string> restoreIpAddresses(const string& s) { vector<string> result; int n = s.size(); // 剪枝:长度必须在 [4,12] if (n < 4 || n > 12) return result; // 枚举三段长度:l1, l2, l3(每段 1~3) for (int l1 = 1; l1 <= 3; ++l1) { if (l1 >= n) break; for (int l2 = 1; l2 <= 3; ++l2) { if (l1 + l2 >= n) break; for (int l3 = 1; l3 <= 3; ++l3) { int l4 = n - l1 - l2 - l3; if (l4 <= 0 || l4 > 3) continue; // 检查四段合法性 if (!isValidPart(s, 0, l1)) continue; if (!isValidPart(s, l1, l2)) continue; if (!isValidPart(s, l1+l2, l3)) continue; if (!isValidPart(s, l1+l2+l3, l4)) continue; // 手动构造结果字符串(避免多次 string 拼接开销) string ip; ip.reserve(16); // IP 最长如 "255.255.255.255" → 15 字符 // 第一段 for (int i = 0; i < l1; ++i) ip += s[i]; ip += '.'; // 第二段 for (int i = l1; i < l1+l2; ++i) ip += s[i]; ip += '.'; // 第三段 for (int i = l1+l2; i < l1+l2+l3; ++i) ip += s[i]; ip += '.'; // 第四段 for (int i = l1+l2+l3; i < n; ++i) ip += s[i]; result.push_back(ip); } } } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { string s; cin >> s; vector<string> ips = restoreIpAddresses(s); if (ips.empty()) { cout << "-1\n"; } else { for (const string& ip : ips) { cout << ip << '\n'; } } } return 0; } 这个好像有点问题
11-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值