Skip to content

Latest commit

 

History

History
102 lines (81 loc) · 2.4 KB

_771. Jewels and Stones.md

File metadata and controls

102 lines (81 loc) · 2.4 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 02, 2024

Last updated : July 01, 2024


Related Topics : Hash Table, String

Acceptance Rate : 89.01 %


Solutions

Java

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;
    }
}

Python

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