771. Jewels and Stones
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 02, 2024
Last updated : July 01, 2024
Related Topics : Hash Table, String
Acceptance Rate : 89.01 %
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set<Character> jw = new HashSet<>();
for (Character c : jewels.toCharArray()) {
jw.add(c);
}
int counter = 0;
for (Character c : stones.toCharArray()) {
if (jw.contains(c)) {
counter++;
}
}
return counter;
}
}
class Solution {
public int numJewelsInStones(String jewels, String stones) {
HashMap<Character, Integer> cnt = new HashMap<>();
for (Character c : stones.toCharArray()) {
cnt.put(c, cnt.getOrDefault(c, 0) + 1);
}
int counter = 0;
for (Character c : jewels.toCharArray()) {
counter += cnt.getOrDefault(c, 0);
}
return counter;
}
}
// Space efficiency O(1)
class Solution {
public int numJewelsInStones(String jewels, String stones) {
int counter = 0;
for (Character stn : stones.toCharArray()) {
for (Character jw : jewels.toCharArray()) {
if (stn == jw) {
counter++;
}
}
}
return counter;
}
}
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jw = set(jewels)
counter: int = 0
for i in stones :
if i in jw :
counter += 1
return counter