题目来源
题目描述
题目解析
思路
先抽象写出框架,bool is4(string),bool is6(string), 先split放到vector,千万不要面向测试用例编程
(1)先判断当前是IPv4地址还是IPv6地址
- 如果包含
.
,说明是IPv4 - 否则是IPv6
(2)非法的IPv4情况:
- 非法的情况:
- 长度为 0 的 IP 地址不是 IPv4 地址;
- 如果 IP 地址以
.
开始或结束,则不是 IPv4 地址;
- 然后将给定的IP地址用
.
作为分隔转成字符串数组 - 如果字符串数组长度不是4,则不是IPv4
- 对于字符串数组的每个元素,需要判断:
- 长度必须在[1, 3]之间
- 长度不能是0:不能出现
12..3.0
- 不包含前导零:当长度大于1时第一个字符不能是
0
- 长度不能是0:不能出现
- 它必须只包含数字,而且值必须在[0, 255]之间
- 长度必须在[1, 3]之间
(3)非法的IPv6情况
- 非法的情况:
- 长度为 0 的 IP 地址不是 IPv6 地址;
- 如果 IP 地址以
:
开始或结束,则不是 IPv6 地址;
- 它包含 8 个部分,用
:
- 将给定的 IP 地址使用
:
作为分隔转成字符串数组; - 对于字符串数组的每个元素,需要判断:
- 长度必须在 [1, 4]之间;
- 它是否只包含数字,或者
a~f
或者A-F
class Solution {
bool isIPv4(string &queryIP){
for (char i : queryIP) {
if(i == '.'){
return true;
}
}
return false;
}
string validIPv4(string &queryIP){
std::string yes = "IPv4", no = "Neither";
auto vec = split(queryIP, '.');
if(vec.size() != 4){
return no;
}
for (auto str : vec) {
if(!(str.size() >= 1 && str.size() <= 4) || (str.size() > 1 && str[0] == '0')){
return no;
}
for(auto ch : str){
if(!(ch >= '0' && ch <= '9')){
return no;
}
}
int num = stoi(str);
if(num > 255){
return no;
}
}
return yes;
}
string validIPv6(string &queryIP){
std::string yes = "IPv6", no = "Neither";
auto vec = split(queryIP, ':');
if(vec.size() != 8){
return no;
}
for (auto str : vec) {
if(!(str.size() >= 1 && str.size() <= 4) ){
return no;
}
for(char ch : str){
if(!( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))){
return no;
}
}
}
return yes;
}
std::vector<std::string> split(std::string &queryIP, char ch){
std::vector<std::string> ans;
std::istringstream ss(queryIP);
std::string tmp;
while (getline(ss, tmp, ch)){
ans.push_back(tmp);
}
return ans;
}
public:
string validIPAddress(string queryIP){
if(queryIP.empty() || queryIP.front() == '.' || queryIP.back() == '.'
|| queryIP.front() == ':' || queryIP.back() == ':'){
return "Neither";
}
return isIPv4(queryIP) ? validIPv4(queryIP) : validIPv6(queryIP);
}
};