246 Strobogrammatic Number
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
The Idea: Good reference: https://oeis.org/A000787. A number is strobogrammatic if it is pair wise palindromic. That is, looking at the vertical reflection of the number, 8 maps with 8, 9 maps with 6, 1 maps with 1, ... etc.
Complexity: O(n) time and O(1) space
class Solution:
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
if not num:
return False
sym_pair = {'8': '8', '6': '9', '9': '6', '1': '1', '0': '0'}
left = 0
right = len(num) - 1
while left <= right:
l_val = num[left]
r_val = num[right]
if l_val not in sym_pair or r_val not in sym_pair:
return False
elif sym_pair[l_val] != r_val or sym_pair[r_val] != l_val:
return False
left += 1
right -= 1
return True
obj = Solution()
print(obj.isStrobogrammatic('69'))
for sn in [str(num) for num in [0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 23, 9199]]:
print(obj.isStrobogrammatic(sn))
Last modified 4yr ago