468. Verifique o endereço IP
médio
222
negócios relacionados
dada uma string queryIP
. Se for um endereço IPv4 válido, retorne-o "IPv4"
; se for um endereço IPv6 válido, retorne-o "IPv6"
; se não for um endereço IP do tipo acima, retorne-o "Neither"
.
Um endereço IPv4 válido tem “x1.x2.x3.x4”
o formato de endereço IP. onde 0 <= xi <= 255
e xi
não pode conter zeros à esquerda. Por exemplo: “192.168.1.1”
, “192.168.1.0”
é um endereço IPv4 válido “192.168.01.1”
e é um endereço IPv4 inválido; “192.168.1.00”
, “[email protected]”
é um endereço IPv4 inválido.
Um endereço IPv6 válido é um “x1:x2:x3:x4:x5:x6:x7:x8”
endereço IP no formato em que:
1 <= xi.length <= 4
xi
é uma string hexadecimal que pode conter números, letras minúsculas em inglês ('a'
to'f'
) e letras maiúsculas em inglês ('A'
to'F'
).- Zeros à esquerda são permitidos em
xi
.
Por exemplo "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
, e "2001:db8:85a3:0:0:8A2E:0370:7334"
são endereços IPv6 válidos e "2001:0db8:85a3::8A2E:037j:7334"
e "02001:0db8:85a3:0000:0000:8a2e:0370:7334"
são endereços IPv6 inválidos.
Exemplo 1:
Entrada: queryIP = "172.16.254.1" Saída: "IPv4" Explicação: Endereço IPv4 válido, retorna "IPv4"
Exemplo 2:
Entrada: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334" Saída: "IPv6" Explicação: Endereço IPv6 válido, retorna "IPv6"
Exemplo 3:
Entrada: queryIP = "256.256.256.256" Saída: "Nenhum" Explicação: Nem um endereço IPv4 nem um endereço IPv6
dica:
queryIP
Consistindo apenas em letras, números, caracteres'.'
e':'
.
A ideia é muito simples, basta realizar a detecção de strings de acordo com as regras, mas sempre há exceções inesperadas, por isso estou depurando.
Vá direto para a resposta:
class Solution {
vector<string> split(const string& str, const string& delim) {
vector<string> res;
if("" == str) return res;
//先将要切割的字符串从string类型转换为char*类型
char * strs = new char[str.length() + 1] ; //不要忘了
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while(p) {
string s = p; //分割得到的字符串转换为string类型
res.push_back(s); //存入结果数组
p = strtok(NULL, d);
}
delete[] d;
delete[] strs;
return res;
}
bool isValid(char ch)
{
if(ch>='0' && ch<='9')
{
return true;
}
else if(ch>='a' && ch<='f')
{
return true;
}
else if(ch>='A' && ch<='F')
{
return true;
}
else
return false;
}
public:
string validIPAddress(string queryIP) {
int len4=0;
int len6=0;
for(auto i:queryIP)
{
if(i=='.')
{
len4++;
}
if(i==':')
{
len6++;
}
}
if(len4>0 && len4!=3)
{
return "Neither";
}
if(len6>0 && len6!=7)
{
return "Neither";
}
vector<string> ipv4Str=split(queryIP,".");
if(ipv4Str.size()==4)
{
if(queryIP[0]=='.' || queryIP[queryIP.size()-1]=='.')
{
return "Neither";
}
bool ipv4Flag=true;
for(auto i:ipv4Str)
{
int a=atoi(i.c_str());
if(a>255)
{
ipv4Flag=false;
break;
}
else
{
string tem=to_string(a);
if(tem!=i)
{
ipv4Flag=false;
break;
}
}
}
if(ipv4Flag)
{
return "IPv4";
}
else
{
return "Neither";
}
}
else
{
vector<string> ipv6Str=split(queryIP,":");
if(ipv6Str.size()==8)
{
if(queryIP[0]!=':' && queryIP[queryIP.size()-1]!=':')
{
bool ipv6Flag=true;
for(auto i:ipv6Str)
{
if(i.size()>4)
{
ipv6Flag=false;
break;
}
else
{
for(auto j:i)
{
if(!isValid(j))
{
ipv6Flag=false;
break;
}
}
}
}
if(ipv6Flag)
{
return "IPv6";
}
else
{
return "Neither";
}
}
else
{
return "Neither";
}
}
else
{
return "Neither";
}
}
}
};
Embora o código não seja muito bom, mas 100% das vezes, verifique se a string tem um 0 inicial, use a conversão para int e depois converta para uma string, se as duas strings forem iguais, não há, caso contrário não há é. Ao mesmo tempo, a função de divisão de string é usada. O bug desta função de divisão é que se não houver nada entre os dois separadores, nenhum dado será retornado. Isso também precisa de melhorias subsequentes.