LeetCode771:Jewels and Stones
阿新 • • 發佈:2019-01-03
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
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