python力扣刷题记录——771. 宝石与石头

题目: 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S
中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 J 中的字母不重复,J 和
S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
在这里插入图片描述

方法一:
执行用时: 24 ms
内存消耗: 14.8 MB

暴力遍历:

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        count = 0
        for i in stones:
            if i in jewels:
                count += 1
        return count

方法二:
执行用时: 20 ms
内存消耗: 14.8 MB

一行代码

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        return sum([jewels.count(i) for i in stones])

有点简单,早点睡觉吧~

猜你喜欢

转载自blog.csdn.net/weixin_45455015/article/details/111602783