题解 | 验证IP地址
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
按照题目中的规则将 ip 地址重新生成一遍:
#include <string>
#include <vector>
#include <array>
#include <cstdio>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <iomanip>
std::vector<std::string> Split(const std::string& str, char delimiter) {
std::vector<std::string> result;
std::size_t start = 0, end = 0;
std::string token;
while ((end = str.find(delimiter, start)) != std::string::npos) {
token = str.substr(start, end - start);
result.push_back(std::move(token));
start = end + 1;
}
result.push_back(str.substr(start));
return result;
}
std::string Join(const std::vector<std::string>& strs, char delimiter) {
if (strs.empty()) {
return "";
}
std::string result = strs[0];
for (int i=1; i<strs.size(); ++i) {
result += delimiter + strs[i];
}
return result;
}
std::string MakeIPv4(const std::array<int, 4>& nums, char delimiter) {
if (nums.empty()) {
return "";
}
std::string result = std::to_string(nums[0]);
for (int i=1; i<nums.size(); ++i) {
result += delimiter + std::to_string(nums[i]);
}
return result;
}
std::string MakeIpv6(const std::array<int, 8>& nums, char delimiter) {
if (nums.empty()) {
return "";
}
std::stringstream ss;
ss << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << nums[0];
for (int i=1; i<nums.size(); ++i) {
ss << delimiter << std::setfill('0') << std::setw(4) << nums[i];
}
return ss.str();
}
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
string solve(string IP) {
// write code here
if (IP[1] == '.' || IP[2] == '.' || IP[3] == '.') {
std::array<int, 4> ip;
if (sscanf(IP.c_str(), "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]) == 4) {
if (ip[0] < 256 && ip[1] < 256 && ip[2] < 256 && ip[3] < 256) {
std::string newIP = MakeIPv4(ip, '.');
if (newIP == IP) {
return "IPv4";
}
}
}
} else if (IP[4] == ':') {
std::vector<std::string> ipSegments = Split(IP, ':');
if (ipSegments.size() == 8) {
std::array<int, 8> ip;
for (int i = 0; i < 8; ++i) {
std::string &ipSegment = ipSegments[i];
if (sscanf(ipSegment.c_str(), "%x", &ip[i])) {
switch(ipSegment.length()) {
case 1:
ipSegment = "000" + ipSegment;
break;
case 2:
ipSegment = "00" + ipSegment;
break;
case 3:
ipSegment = "0" + ipSegment;
break;
case 4:
break;
default:
return "Neither";
}
}
}
std::string formattedIP = Join(ipSegments, ':');
std::transform(formattedIP.begin(), formattedIP.end(), formattedIP.begin(), ::toupper);
std::string newIP = MakeIpv6(ip, ':');
if (formattedIP == newIP) {
return "IPv6";
}
}
}
return "Neither";
}
};
查看16道真题和解析