Leetcode 468. 验证IP地址 字符串解析验证判断

这一道题如果面试遇到,首先问面试管能否用split函数。

是IPV4的必要条件是字符串有三个点.先按点进行解析,然后对每一部分进行解析即可。

每一步分的长度必须大于0,小于等于3。第一位不能是0,只能是纯数字,而且不能超过255

    def validIPv4(self, IP: str) -> bool:
        if IP.count('.')!=3:
            return False
        nums = IP.split('.')
        for x in nums:
            if len(x)==0 or len(x)>3:
                return False
            if x[0]=='0' and len(x)>1 or not x.isdigit() or int(x)>255:
                return False
        return True

IPv6有7个:,分为八部分,只要字符全都在123456789abcdeABCDE中即可。

    def validIPv6(self, IP:str) ->bool:
        if IP.count(':')!=7:
            return False
        hexdigits = '0123456789abcdefABCDEF'
        nums = IP.split(':')
        for x in nums:
            if len(x)==0 or len(x)>4 or not all(c in hexdigits for c in x):
                return False
        return True

完整代码:

class Solution:
    def validIPAddress(self, IP: str) -> str:
        if IP.count('.')==3 and self.validIPv4(IP):
            return "IPv4"
        if IP.count(':')==7 and self.validIPv6(IP):
            return "IPv6"
        return "Neither"

    def validIPv4(self, IP: str) -> bool:
        if IP.count('.')!=3:
            return False
        nums = IP.split('.')
        for x in nums:
            if len(x)==0 or len(x)>3:
                return False
            if x[0]=='0' and len(x)>1 or not x.isdigit() or int(x)>255:
                return False
        return True

    def validIPv6(self, IP:str) ->bool:
        if IP.count(':')!=7:
            return False
        hexdigits = '0123456789abcdefABCDEF'
        nums = IP.split(':')
        for x in nums:
            if len(x)==0 or len(x)>4 or not all(c in hexdigits for c in x):
                return False
        return True

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108350041