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.
1def numJewelsInStones(jewels, stones):
2 jewel_set = set(jewels)
3 return sum(stone in jewel_set for stone in stones)
4
5print(numJewelsInStones('aA', 'aAAbbbb'))
The Python solution utilizes the set data structure, providing efficient O(1) lookups for each stone. The use of a generator expression with sum()
simplifies the counting process.
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.