模拟,遍历 ip4 和 ip6 的每组数 ip4 时有非数字字符、数据范围、首字符为0,字符串长度大等均无效 ipv6 时非16进制数、数据范围、字符串长度大等无效

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
    def ipv4(self, ip: str) -> str:
        flag = True
        for x in ip.split("."):
            if len(x) > 3:
                flag = False
                break
            for xi in x:
                if not "0" <= xi <= "9":
                    flag = False
                    break
            if not flag:
                break
            if x[0] == "0" or int(x) < 0 or int(x) > 255:
                flag = False
                break
        return "IPv4" if flag else "Neither"
    
    def ipv6(self, ip: str) -> str:
        def check(digit):
            try:
                res = int(digit, 16)
                return True
            except Exception:
                return False
        flag = True
        for x in ip.split(":"):
            if not x or len(x) > 4 or not check(x.upper()) or int(x.upper(), 16) < 0 or int(x.upper(), 16) > 65536:
                flag = False
                break
        return "IPv6" if flag else "Neither"
    
    def solve(self , IP: str) -> str:
        # write code here
        if ":" in IP:
            # ip6
            if len(IP.split(":")) != 8: return "Neither"
            return self.ipv6(IP)
        elif "." in IP:
            if len(IP.split(".")) != 4: return "Neither"
            return self.ipv4(IP)
        else:
            return "Neither"