【题目】
给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
【示例 1】
输入: J = “aA”, S = “aAAbbbb”
输出: 3
【示例 2】
输入: J = “z”, S = “ZZ”
输出: 0
【注意】
S 和 J 最多含有50个字母。
J 中的字符不重复。
【代码】
【Python】
【方法1:使用数据结构dict】
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
cnt=dict(Counter(stones))
c=0
for key in cnt:
if key in jewels:
c+=cnt[key]
return c
【方法2:最质朴的方式】遍历stones字符串,挨个字符判断是否存在于jewels中
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
c=0
for s in stones:
if s in jewels:
c+=1
return c
【方法3:一行代码】
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return sum(s in jewels for s in stones)
【方法4:使用数据结构set】
执行用时:
32 ms, 在所有 Python3 提交中击败了95.04%的用户
内存消耗:
14.8 MB, 在所有 Python3 提交中击败了50.38%的用户
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jewelsSet = set(jewels)
return sum(s in jewelsSet for s in stones)