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
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
LeetCode:链接
简单讲就是,给你一个代表不同宝石的字符串,和一个代表石头的字符串,从石头字符串里找出属于宝石的石头,并返回个数。
注意,区分大小写即a和A不一样。
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
je_dict = {}
for i in J:
je_dict[i] = 1
count = 0
for i in S:
if i in je_dict:
count += 1
return count
但是貌似set更快一些。
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
jewels = set(J)
count = 0
for i in S:
if i in jewels:
count += 1
return count