Run ID | 作者 | 问题 | 语言 | 测评结果 | 分数 | 时间 | 内存 | 代码长度 | 提交时间 |
---|---|---|---|---|---|---|---|---|---|
136619 | | 复原 IP 地址 | C++ | 通过 | 100 | 0 MS | 260 KB | 1666 | 2024-03-09 11:12:34 |
#include <iostream> #include <vector> #include <string> using namespace std; bool isValidPart(const string& s, int start, int end) { int len = end - start + 1; // Check for leading zeros if (len > 1 && s[start] == '0') return false; // Convert string to integer int num = stoi(s.substr(start, len)); // Check if number is between 0 and 255 return num >= 0 && num <= 255; } void backtrack(string& s, int start, int parts, vector<string>& result, string current) { // If reached the end of the string and used 4 parts, add current to result if (start == s.length() && parts == 4) { result.push_back(current); return; } // If reached the end of the string or used all 4 parts, return if (start == s.length() || parts == 4) return; // Try adding '.' after each character for (int len = 1; len <= 3 && start + len <= s.length(); ++len) { string part = s.substr(start, len); if (isValidPart(s, start, start + len - 1)) { if (current.empty()) { backtrack(s, start + len, parts + 1, result, part); } else { backtrack(s, start + len, parts + 1, result, current + "." + part); } } } } vector<string> restoreIpAddresses(string s) { vector<string> result; backtrack(s, 0, 0, result, ""); return result; } int main() { string s; cin >> s; vector<string> validIPs = restoreIpAddresses(s); for (const string& ip : validIPs) { cout << ip << endl; } return 0; }