Sponsored
Sponsored
This approach leverages a Set (or a HashSet in some languages) for quickly determining if a stone is a jewel. The idea is to store all the jewel types in a set, then iterate through each stone, checking if the stone is in the set. If it is, we increment our count of jewels found.
Time Complexity: O(n * m), where n is the number of stones and m is the number of jewels. Space Complexity: O(1), since no extra space is used other than for the input strings.
1function numJewelsInStones(jewels, stones) {
2 const jewelSet = new Set(jewels);
3 let count = 0;
4 for (const stone of stones) {
5 if (jewelSet.has(stone)) {
6 count++;
7 }
8 }
9 return count;
10}
11
12console.log(numJewelsInStones('aA', 'aAAbbbb'));
The JavaScript solution establishes a Set
of jewels and iterates through the stones, incrementing a count for each stone that appears in the set. The use of a set ensures fast membership checking.
This approach uses an array to quickly map each character to an index, allowing us to count frequencies of jewels in the stones. Since the input is restricted to English letters, a fixed-size array of 52 (for each upper and lower case letter) is adequate.
Time Complexity: O(n + m), where n is the length of jewels and m is the length of stones. Space Complexity: O(1), using a fixed-size array for character mapping.
1#include <vector>
int numJewelsInStones(std::string jewels, std::string stones) {
std::vector<int> jewelCount(52, 0);
int count = 0;
for (char jewel : jewels) {
if (jewel >= 'a' && jewel <= 'z')
jewelCount[jewel - 'a'] = 1;
else
jewelCount[jewel - 'A' + 26] = 1;
}
for (char stone : stones) {
if (stone >= 'a' && stone <= 'z') {
count += jewelCount[stone - 'a'];
} else {
count += jewelCount[stone - 'A' + 26];
}
}
return count;
}
int main() {
std::string jewels = "aA";
std::string stones = "aAAbbbb";
std::cout << numJewelsInStones(jewels, stones) << std::endl;
return 0;
}
In C++, a std::vector
is used for indexing jewels, allowing quick access to determine if a stone is a jewel. The solution efficiently maps both upper and lowercase letters to an index.