题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

class Solution:
    def solve(self , IP: str) -> str:
        # write code here
        def isValid4(s):
            lst = s.split('.')
            if len(lst) != 4:
                return False
            for num in lst:
                if not num:
                    return False
                if not num.isdigit():
                    return False
                if int(num) != 0 and num[0] == '0':
                    return False
                if int(num) < 0 or int(num) > 255:
                    return False
            return True
        
        def isValid6(s):
            lst = s.split(':')
            if len(lst) != 8:
                return False
            for num in lst:
                if not num:
                    return False
                if len(num) > 4:
                    return False
                for c in num:
                    if c.isalpha():
                        if ord('f') < ord(c) <= ord('z') or ord('F') < ord(c) <= ord('Z'):
                            return False
            return True
        
        if isValid4(IP): return 'IPv4'
        elif isValid6(IP): return 'IPv6'
        else: return 'Neither'
        

全部评论

相关推荐

点赞 评论 收藏
分享
投递长鑫存储等公司8个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务