题目:
您得到的字符串J代表宝石的宝石类型,而S代表您拥有的宝石。 S中的每个字符都是您拥有的一块石头。 您想知道您拥有多少宝石也是珠宝。
J中的字母是不同的,并且J和S中的所有字符都是字母。 字母区分大小写,因此“ a”被认为与“ A”不同。
Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
S
and J
will consist of letters and have length at most 50.J
are distinct.【解法一】
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: n = 0 for i in J: for j in S: if i == j: n += 1 return n
def numJewelsInStones(self, J, S): return sum(map(J.count, S)) def numJewelsInStones(self, J, S): return sum(map(S.count, J))
return sum(s in J for s inS) #is equal to: int res = 0 for s in S: if s in setJ: res += 1 return res
def numJewelsInStones(self, J, S): return sum([s in J for s in S])
Runtime: 20 ms, faster than 98.42% of Python3 online submissions for Jewels and Stones.
【解法】
用hash table的思想。
def numJewelsInStones(self, J, S): charToFreqS = {} # Map character to its frequency in S. numJewels = 0 # Total number of jewels. for ch in S: if ch not in charToFreqS: charToFreqS[ch] = 1 else: charToFreqS[ch] += 1 for ch in J: if ch in charToFreqS: numJewels += charToFreqS[ch] return numJewels
【LeetCode】【HashTable】jewels and stones
原文:https://www.cnblogs.com/jialinliu/p/13216670.html