Problem Statement:
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 different from "A".
Example:
Input: jewels = “aA”, stones = “aAAbbbb”
Output: 3
Input: jewels = “z”, stones = “ZZ”
Output: 0
Constraints:
- 1 ≤ jewels.length, stones.length ≤ 50
- jewels and stones consist of only English letters
- All characters in
jewelsare unique
Approach 1 :
- Use two nested loops: Outer loop over
stones, inner loop overjewels. - If a character in
stonesmatches any injewels, increment the count. - Break inner loop once matched to avoid redundant checks.
Time and Space Complexity:
- Time Complexity: O(m × n) — where
mis the length ofstonesandnis the length ofjewels. - Space Complexity: O(1) — constant extra space.
var numJewelsInStones = function(jewels, stones) {
let count = 0;
for (let i = 0; i < stones.length; i++) {
for (let j = 0; j < jewels.length; j++) {
if (jewels[j] === stones[i]) {
++count;
break;
}
}
}
return count;
};
int numJewelsInStones(char* jewels, char* stones) {
int count = 0;
for (int i = 0; stones[i] != '\0'; i++) {
for (int j = 0; jewels[j] != '\0'; j++) {
if (stones[i] == jewels[j]) {
count++;
break;
}
}
}
return count;
}
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
int count = 0;
for (char s : stones) {
for (char j : jewels) {
if (s == j) {
count++;
break;
}
}
}
return count;
}
};
class Solution {
public int numJewelsInStones(String jewels, String stones) {
int count = 0;
for (int i = 0; i < stones.length(); i++) {
for (int j = 0; j < jewels.length(); j++) {
if (stones.charAt(i) == jewels.charAt(j)) {
count++;
break;
}
}
}
return count;
}
}
class Solution(object):
def numJewelsInStones(self, jewels, stones):
count = 0
for s in stones:
for j in jewels:
if s == j:
count += 1
break
return count
public class Solution {
public int NumJewelsInStones(string jewels, string stones) {
int count = 0;
foreach (char s in stones) {
foreach (char j in jewels) {
if (s == j) {
count++;
break;
}
}
}
return count;
}
}
