Leetcode 771. Jewels and Stones
You’re given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so “a” is considered a different type of stone from “A”.
jewels and stones strings be empty?
jewels string?
jewels is unique.jewels and stones?
jewels string into a HashSet for O(1) average-time complexity lookups.stones string, check if it exists in the HashSet of jewels.stones string.import java.util.HashSet;
public class Solution {
public int numJewelsInStones(String jewels, String stones) {
// Create a HashSet from jewels characters
HashSet<Character> jewelSet = new HashSet<>();
for (char jewel : jewels.toCharArray()) {
jewelSet.add(jewel);
}
// Count jewels in stones
int count = 0;
for (char stone : stones.toCharArray()) {
if (jewelSet.contains(stone)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.numJewelsInStones("aA", "aAAbbbb")); // Output: 3
System.out.println(solution.numJewelsInStones("z", "ZZ")); // Output: 0
System.out.println(solution.numJewelsInStones("", "ZZ")); // Output: 0
System.out.println(solution.numJewelsInStones("z", "")); // Output: 0
}
}
jewels string.stones string.jewels string.jewels string, which means it will be O(J).This solution efficiently calculates the number of jewels in the stones string using a HashSet for optimization.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?