You're given strings
J
representing the types of stones that are jewels, andS
representing the stones you have. Each character inS
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 inJ
andS
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: 3Example 2:
Input: J = "z", S = "ZZ" Output: 0
J的每个字符都是一种宝石类型,S是所拥有的石头串,问石头串里有多少宝石
1 使用字典 ,先计数再求和
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = collections.Counter(S)
num = 0
for x in J:
num += count.setdefault(x,0)
return num
2 直接遍历求和
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
num = 0
for x in S:
if x in J: num += 1
return num