LeetCode 771: Jewels and Stones Solution

Master LeetCode problem 771 (Jewels and Stones), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

771. Jewels and Stones

Problem Explanation

Explanation

To solve this problem, we can iterate through each stone in the stones string and check if it is present in the jewels string. If it is present, we increment a counter to keep track of the number of stones that are jewels. We can use a Set in Java or a unordered_set in C++ to store the types of jewels for efficient lookup. The time complexity of this approach is O(n), where n is the length of the stones string, and the space complexity is O(m), where m is the number of unique jewels.

Solution Code

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        Set<Character> jewelSet = new HashSet<>();
        for (char jewel : jewels.toCharArray()) {
            jewelSet.add(jewel);
        }
        
        int count = 0;
        for (char stone : stones.toCharArray()) {
            if (jewelSet.contains(stone)) {
                count++;
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 771 (Jewels and Stones)?

This page provides optimized solutions for LeetCode problem 771 (Jewels and Stones) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 771 (Jewels and Stones)?

The time complexity for LeetCode 771 (Jewels and Stones) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 771 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 771 in Java, C++, or Python.

Back to LeetCode Solutions