Leetcode 刷题 - 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.


首先就想一下180°转了之后能够凑成一样的数字是什么。0,1,8,6-9。其中6-9必须是成对的,不要问为什么。


这题很像那些问你回文的题目,二分之后对称位置的数字的组合必须是符合"00","11","88","69","96"。

class Solution(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool
        """
        for i in range(len(num)/2+1):
            if num[i] + num[-i-1] not in "696001188":
                return False
        return True

因为只要是对称位置上下调转相同,或者是"69","96"对,就满足要求。所以只需要取对称位,然后判断是否是那些数字即可。因为会全部取到,所以并不担心取到"60"这样的数字,之后的反取"06"会false掉。


======================

很赞的方法

def isStrobogrammatic(self, num):
    return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)/2+1))

其中的num[~i],index位取反是亮点。


Some others:

def isStrobogrammatic(self, num):
    return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)))

def isStrobogrammatic(self, num):
    return all(map('696 00 11 88'.count, map(operator.add, num, num[::-1])))

def isStrobogrammatic(self, num):
    return all(p in '696 00 11 88' for p in map(operator.add, num, num[::-1]))

def isStrobogrammatic(self, num):
    return set(map(operator.add, num, num[::-1])) <= set('69 96 00 11 88'.split())

def isStrobogrammatic(self, num):
    return set(map(operator.add, num, num[::-1])) <= {'69', '96', '00', '11', '88'}

def isStrobogrammatic(self, num):
    return set(map(''.join, zip(num, num[::-1]))) <= {'69', '96', '00', '11', '88'}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值