leetcode 771. Jewels and Stones(python)

332 阅读1分钟

描述

You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3	

Example 2:

Input: jewels = "z", stones = "ZZ"
Output: 0

Note:

  • 1 <= jewels.length, stones.length <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

解析

根据题意,只需要使用字典结构 c 统计 stones 中的字符及其出现个数,然后遍历 jewels ,如果其中的字符在 c 中出现,则取出对应的出现个数与 res 相加,遍历结束得到的最后的结果就是答案。

解答

class Solution(object):
    def numJewelsInStones(self, jewels, stones):
        """
        :type jewels: str
        :type stones: str
        :rtype: int
        """
        res = 0
        c = collections.Counter(stones)
        for j in jewels:
            if j in c:
                res += c.get(j)
        return res
        	      
		

运行结果

Runtime: 12 ms, faster than 96.47% of Python online submissions for Jewels and Stones.
Memory Usage: 13.6 MB, less than 8.33% of Python online submissions for Jewels and Stones.

原题链接:leetcode.com/problems/je…

您的支持是我最大的动力