原题地址:https://leetcode-cn.com/problems/validate-ip-address/submissions/
解题方案:
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。
然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。
示例 1:
输入: "172.16.254.1"
输出: "IPv4"
解释: 这是一个有效的 IPv4 地址, 所以返回 "IPv4"。 示例 2:
输入: "2001:0db8:85a3:0:0:8A2E:0370:7334"
输出: "IPv6"
解释: 这是一个有效的 IPv6 地址, 所以返回 "IPv6"。 示例 3:
输入: "256.256.256.256"
输出: "Neither"
解释: 这个地址既不是 IPv4 也不是 IPv6 地址。
题目描述:
class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ def checkIPv4(IP): nums = IP.split(".") if len(nums) != 4: return False for num in nums: if not num or (not num.isdecimal()) or (num[0] == '0' and len(num) != 1) or int(num) > 255: return False return True def checkIPv6(IP): IP = IP.lower() if "::" in IP: return False nums = IP.split(":") valid = "0123456789abcdef" print(nums) if len(nums) != 8: return False for num in nums: if not num: continue if len(num) >= 5: return False for n in num: if n not in valid: return False return True if checkIPv4(IP): return "IPv4" elif checkIPv6(IP): return "IPv6" else: return "Neither" class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ if not IP: return "Neither" V4 = True if ":" in IP: V4 = False if V4: helper = IP.split(".") if len(helper) !=4: return "Neither" for item in helper: if not item: return "Neither" if item[0] == '0' and len(item) > 1: return "Neither" for i in item: if not i.isdigit(): return "Neither" if int(item) > 255 or int(item) < 0: return "Neither" return "IPv4" else: helper = IP.split(":") if len(helper)!=8: return "Neither" for item in helper: if len(item)>4: return "Neither" if len(item) == 0: return "Neither" for i in range(len(item)): if item[i].isdigit(): continue if item[i] >= "A" and item[i] < "G": continue if item[i] >='a' and item[i] <'g': continue else: return "Neither" return "IPv6"
