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.
1#include <iostream>
2#include <unordered_set>
3
4int numJewelsInStones(std::string jewels, std::string stones) {
5 std::unordered_set<char> jewelSet(jewels.begin(), jewels.end());
6 int count = 0;
7 for (char stone : stones) {
8 if (jewelSet.count(stone)) {
9 count++;
10 }
11 }
12 return count;
13}
14
15int main() {
16 std::string jewels = "aA";
17 std::string stones = "aAAbbbb";
18 std::cout << numJewelsInStones(jewels, stones) << std::endl;
19 return 0;
20}
The C++ solution uses an unordered_set
to store the jewels, allowing for O(1) average-time complexity lookups when iterating through the stones. We increment our count for each stone that is found in the set.
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
This C solution uses an array of size 52 to represent each letter as a potential jewel. This approach handles both uppercase and lowercase characters distinctly, using ASCII arithmetic to map letters to indices.