题目:
You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is 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”.
大致思路:
一、直接使用count函数
二、遍历S,若J中存在,则累加
三、字典Counter函数
法一代码:
def numJewelsInStones(J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
return sum(S.count(i) for i in J)
法二代码:
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
counts = 0
for i in S:
if i in J:
counts += 1
return counts
法三代码:
def numJewelsInStones(J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
tmp = collections.Counter(S)
res = 0
for i in J:
res += a[i]
return res
2019.2.28 武汉