Python solution yo


  • 0
    A
    class Solution(object):
        def validIPAddress(self, ip):
            """
            :type IP: str
            :rtype: str
            """
            ipv4 = ip.split(".")
            ipv6 = ip.split(":")
            if len(ipv4) == 4 and self.validateIPv4(ipv4):
                return "IPv4"
            elif len(ipv6) == 8 and self.validateIPv6(ipv6):
                return "IPv6"
            else:
                return "Neither"
                
        def validateIPv4(self, segments):
            digits = set("1234567890")
            for s in segments:
                # segment too long or too short
                if len(s) > 3 or len(s) == 0:
                    return False
        
                # segment has leading 0
                if len(s) > 1 and s[0] == "0":
                    return False
        
                # segment contains non-numeric digits
                if not set(s) < digits:
                    return False
        
                # segment is not an int between 0 and 255 inclusive
                if int(s) > 255 or int(s) < 0:
                    return False
            return True
            
        def validateIPv6(self, segments):
            hexDigits = set("1234567890abcdefABCDEF")
            for s in segments:
                # segment too long or too short
                if len(s) > 4 or len(s) == 0:
                    return False
        
                # segment contains non-hexadecimal digits
                if not set(s) < hexDigits:
                    return False
            return True
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.