topic:
Given the string J
represents the type of gem stones, strings and S
representatives of stones you have. S
Each character represents a type of stone you have, you want to know the stone you have in how many gems.
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.
J
The letters are not repeated, J
and S
all characters are letters. Case sensitive, therefore "a"
, and "A"
different types of stones.
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:
输入: J = "aA", S = "aAAbbbb"
输出: 3
Example 2:
输入: J = "z", S = "ZZ"
输出: 0
note:
S
AndJ
contain up to 50 letters.J
The characters are not repeated.
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
Problem-solving ideas:
Set J to set, to traverse the S (Set lookup because complexity is constant)
Java:
class Solution {
public int numJewelsInStones(String J, String S) {
Set<Character> set = new HashSet<>();
for (char c : J.toCharArray())
set.add(c);
int count = 0;
for (char c : S.toCharArray())
if (set.contains(c)) count++;
return count;
}
}
Python:
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count = 0
hash_set = set(J)
for c in S:
if c in hash_set:
count += 1
return count
Welcome attention to micro-channel public public .. No: Love Bug write