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.
Example 1:
Input: num = "69" Output: true
Example 2:
Input: num = "88" Output: true
Example 3:
Input: num = "962" Output: false
Example 4:
Input: num = "1" Output: true
TC: O(N) SC:O(1)
Solution 1:
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
if not num:
return True
map = {'0':'0','1':'1','6':'9','8':'8','9':'6','2':'','3':'','4':'','5':'','7':''}
i = 0
j = len(num)-1
while i<=j:
if num[i] != map[num[j]]:
return False
i+=1
j-=1
return True
Solution 2:
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
if not num:
return True
map = {'0':'0','1':'1','6':'9','8':'8','9':'6'}
i = 0
j = len(num)-1
while i<=j:
if num[j] not in map or num[i] != map[num[j]]:
return False
i+=1
j-=1
return True
No comments:
Post a Comment