771. Jewels and Stones leetcode python

开启python刷题模式,用不惯leetcode。

771. Jewels and Stones

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

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.class Solution(object):


  • python成员运算符in的用法:
  • a in b

    如果在指定序列b中找到元素a,则返回True,否则返回False。not in相反。

    生成器的用法:

    形如

    [python]  view plain  copy
    1. (x for x in range(5))  

    的语句即为生成器。注意生成器外围的一对圆括号。如果换成[]就变成了列表生成器。


class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        return sum(s in J for s in S)

发布了192 篇原创文章 · 获赞 27 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/lovely_girl1126/article/details/79509537