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.
1using System;
2using System.Collections.Generic;
3
4class Program {
5 public static int NumJewelsInStones(string jewels, string stones) {
6 var jewelSet = new HashSet<char>(jewels);
7 int count = 0;
8 foreach (var stone in stones) {
9 if (jewelSet.Contains(stone)) {
10 count++;
11 }
12 }
13 return count;
14 }
15
16 static void Main() {
17 Console.WriteLine(NumJewelsInStones("aA", "aAAbbbb"));
18 }
19}
In C#, a HashSet
stores jewel types and allows for efficient membership testing for each stone. The count is accumulated using a simple loop.
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.