给你一个字符串 jewels
代表石头中宝石的类型,另有一个字符串 stones
代表你拥有的石头。 stones
中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
字母区分大小写,因此 "a"
和 "A"
是不同类型的石头。
示例 1:
输入:jewels = "aA", stones = "aAAbbbb" 输出:3
示例 2:
输入:jewels = "z", stones = "ZZ" 输出:0
提示:
1 <= jewels.length, stones.length <= 50
jewels
和stones
仅由英文字母组成jewels
中的所有字符都是 唯一的
哈希表实现。
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
s = set(jewels)
return sum([1 for c in stones if c in s])
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set<Character> s = new HashSet<>();
for (char c : jewels.toCharArray()) {
s.add(c);
}
int res = 0;
for (char c : stones.toCharArray()) {
res += (s.contains(c) ? 1 : 0);
}
return res;
}
}
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
unordered_set<char> s;
for (char c : jewels) {
s.insert(c);
}
int res = 0;
for (char c : stones) {
res += s.count(c);
}
return res;
}
};
func numJewelsInStones(jewels string, stones string) int {
s := make(map[rune]bool)
for _, c := range jewels {
s[c] = true
}
res := 0
for _, c := range stones {
if s[c] {
res++
}
}
return res
}