코딩 알고리즘 문제/Leetcode

468. Validate IP Address (String)

highlightmoon 2025. 10. 28. 11:14
반응형

링크 - https://leetcode.com/problems/validate-ip-address/description/

난이도 - Medium

Intuition

우리는 각 ip를 그에 맞는 함수에 적용시켜 문제를 풀 수 있다.

Code

class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        counter = Counter(queryIP)
        if counter.get(".", 0) == 3:
            return self.validateIPv4(queryIP)
        elif counter.get(":", 0) == 7:
            return self.validateIPv6(queryIP)
        else:
            return "Neither"

    def validateIPv4(self, ip):
        nums = ip.split(".")
        for num in nums:
            if len(num) == 0 or len(num) > 3:
                return "Neither"
            if len(num) > 1 and num[0] == "0":
                return "Neither"
            if not num.isdigit():
                return "Neither"
            if int(num) > 255:
                return "Neither"
        return "IPv4"

    def validateIPv6(self, ip):
        nums = ip.split(":")
        hexdigits = "0123456789abcdefABCDEF"
        for num in nums:
            if len(num) == 0 or len(num) > 4:
                return "Neither"
            for c in num:
                if c not in hexdigits:
                    return "Neither"
        return "IPv6"

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

반응형