Author: 18th CYL
Date: 2020-10-2
Tag: match count leetcode brute force solution
Title description:
The given string J represents the type of gem in the stone, and the string S represents the stone you own. Each character in S represents a type of stone you own, and you want to know how many of the stones you own are gems.
The letters in J are not repeated, and all the characters in J and S are letters. Letters are case sensitive, so "a" and "A" are different types of stones.
Example:
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
note:
S and J can contain up to 50 letters.
The characters in J are not repeated.
Problem solving ideas
1. Count the number of stones in each hand
2. It will be the sum of gems
Code
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
if S == "":
return 0
num = 0 #宝石的数量
S_dict = {} #各个元素数量
for key in S:
S_dict[key] = S_dict.get(key,0) + 1
# print(S_dict.keys())
for i in list(J):
if i in S_dict.keys():
num += S_dict[i]
return num