Python solution with detailed explanation


  • 0
    G

    Solution

    Strobogrammatic Number https://leetcode.com/problems/strobogrammatic-number/

    1. Visualize what 180 degree of rotation does. "69". Lets call the new string formed by 180 degree of rotation of digit x as rot(x). So "69" results in rot(9)rot(6).
    2. Only 1,6,8,9,0 form themselves with 180 degress of rotation. If any other string is found, it is an error.
    3. Using 1 and 2, formulate a solution.
    class Solution(object):
        def isStrobogrammatic(self, num):
            """
            :type num: str
            :rtype: bool
            """
            smap = {"1":"1", "6":"9", "8":"8", "9":"6", "0":"0"}
            st, e = 0, len(num)-1
            while st <= e:
                if num[st] not in smap or smap[num[st]] != num[e]:
                    return False
                st, e = st+1, e-1
            return True
    

Log in to reply
 

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