题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
def solve(self, IP: str) -> str:
if "." in IP:
arr = IP.split(".")
a = 0
for i in arr:
try:
if len(arr) == 4 and 0 <= int(i) <= 255 and int(i[0]):
a += 1
except:
return "Neither"
if a == 4:
return "IPv4"
return "Neither"
elif ":" in IP:
arr = IP.split(":")
a = 0
for ip in arr:
if (
ip == ""
or len(ip) > 4
or IP[-1] == ":"
):
return "Neither"
try:
int(ip, 16)
except:
return "Neither"
return "IPv6"