题目描述
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”.
例子
Example 1:
Input: J = “aA”, S = “aAAbbbb”
Output: 3
Example 2:
Input: J = “z”, S = “ZZ”
Output: 0
解释
给两个S字符串J和S,J里面的每一个字符都代表一个珠宝的样式,S里面的每一个字符都代表你现在手里的石头。现在就是要计算你手里的石头里有多少个是珠宝。比如第一个例子,'a’和’A’是珠宝,所以S中’a’出现了一次,'A’出现了两次,返回1 + 2 = 3。
思路
这题很简单,我的思路是用字典存S中每个字符出现过的次数,再遍历J,把J中每一个字符作为key去字典中查找,把value相加即为最终答案。这样我们每次查找就等于是看某一个珠宝的字符在我手里的石头中出现了几次。
代码
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
#Python自带的Counter,可以直接对字符计数。
#具体可以用下面链接查查文档。
#https://docs.python.org/2/library/collections.html
import collections
c = collections.Counter(S)
#遍历J中每个字符并把value相加
ans = 0
for i in range(len(J)):
ans += c[J[i]]
return ans