Simple python solution


  • 0
    A

    I split the ip address into groups split by ":" or "." (based on whether the latter is in the
    string).
    I then make sure I have the exact number of groups I need (4 for IPv4, 6 for IPv6), and then
    test each group to make sure they have a valid format.

    hexa_numbers = {'0', '1', '2', '3', 
                    '4', '5', '6', '7', 
                    '8', '9', 'A', 'B', 
                    'C', 'D', 'E', 'F', 
                    'a', 'b', 'c', 'd', 
                    'e', 'f'}
    
    class Solution(object):
    
        def is_valid4(self, group):
            if group.startswith('0') and len(group) > 1:
                return False
            if not group.isdigit():
                return False
            nb = int(group)
            return nb >= 0 and nb <= 255
    
        def is_valid6(self, group):
            if len(group) > 4 or len(group) == 0:
                return False
            return all([g in hexa_numbers for g in group])
          
        def validIPAddress(self, IP):
            if ':' in IP:
                groups = IP.split(':')
                if len(groups) != 8:
                    return "Neither"
                for group in groups:
                    if not self.is_valid6(group):
                        return "Neither"
                return "IPv6"
            else:
                groups = IP.split('.')
                if len(groups) != 4:
                    return "Neither"
                for group in groups:
                    if not self.is_valid4(group):
                        return "Neither"
                return "IPv4"
    

Log in to reply
 

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