코딩 알고리즘 문제/Leetcode

246. Strobogrammatic Number (Hash Table, Two Pointers, String)

highlightmoon 2025. 10. 22. 08:06
반응형

링크 - https://leetcode.com/problems/strobogrammatic-number/description/?envType=company&envId=facebook&favoriteSlug=facebook-thirty-days

난이도 - Easy

Intuition

Pair를 만드는 hash table를 만들고, left와 right포인터를 만들어 글자를 비교하면서 푸는 문제이다.

Code

class Solution:
    def isStrobogrammatic(self, num: str) -> bool:
        pairs = {
            '0': '0', 
            '1': '1', 
            '8': '8', 
            '6': '9', 
            '9': '6'
        }

        left = 0
        right = len(num) - 1
        while left <= right:
            if num[left] not in pairs or num[right] not in pairs:
                return False
            if num[left] != pairs[num[right]]:
                return False
            left += 1
            right -= 1

        return True

Complexity

Time Complexity: O(N) num을 left와 right로 linear하게 비교하기 때문이다.

Space Complexity: O(1) 

반응형