Validate IP Address

Problem Id: 468 Difficulty: Medium


Intuition

Solution


class Solution:
    def _validIpv4(self, ip):
        values = ip.split('.')
        if len(values) != 4:
            return False
        for each in values:
            for c in each:
                if c not in string.digits:
                    return False
            if not each:
                return False
            if not (0 <= int(each) <= 255):
                return False
            if each[0] == '0' and len(each) > 1:
                return False
        return True

    def _validIpv6(self, ip):
        values = ip.split(':')
        if len(values) != 8:
            return False
        values = [v.lower() for v in values]
        for each in values:
            if not each:
                return False
            if len(each) > 4:
                return False
            for c in each:
                if c not in (string.digits + 'abcdef'):
                    return False
        return True

    def validIPAddress(self, IP: str) -> str:
        if '.' in IP:
            return 'IPv4' if self._validIpv4(IP) else 'Neither'
        return 'IPv6' if self._validIpv6(IP) else 'Neither'