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


