# Jewels and Stones

### Question

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

Example 1

 Input: J = "aA", S = "aAAbbbb" Output: 3 

Example 2

 Input: J = "z", S = "ZZ" Output: 0 

Note: S and J will consist of letters and have length at most 50. The characters in J are distinct.

See on Leetcode

### Solution

class Solution {

public int numJewelsInStones(String J, String S) {

// split string to jewels character array
char[] jewels = J.toCharArray();

// split string to all stones character array
char[] allStones = S.toCharArray();

int jewelCount = 0;
Map < Character, Integer > allStonesMap = new HashMap < > ();

/* Iterate through all stones, populate the map with
the stone type as key and its count as value
*/
for (int i = 0; i < allStones.length; i++) {
if (allStonesMap.containsKey(allStones[i])) {
allStonesMap.put(allStones[i], allStonesMap.get(allStones[i]) + 1);
} else {
allStonesMap.put(allStones[i], 1);
}
}

/* Iterate through the jewels and find if any jeweltype matches with the
stones we have in the map, if there's a match then increment the jewelCount
with the stone count in the all stones map */
for (int i = 0; i < jewels.length; i++) {
if (allStonesMap.containsKey(jewelType[i])) {
jewelCount = jewelCount + allStonesMap.get(jewelType[i]);
}
}

return jewelCount;

}
}

### Test Cases

• Jewel(J) has at least a match from the stones(S), where there is a mix of uppercase and lower case of same letter in J and S.
• Jewel(J) has no match from the stones(S), where jewels is in lower case of a letter and stone is in upper case of the same letter.
• Jewel(J) has few match from the stones(S)
• All the jewel(J) match from the stones(S)
• J and S have UTF-8 special characters, characters from different languages, and symbols as matches.
• J and S are long strings with some jewels(J) matching in stones(S).

Although the code above does not handle below test cases it’s worthwhile to test for all the below cases in case you’re asked about this in an interview.

• Jewel(J) as empty, stones(S) as null.
• Jewel(J) as null, stones(S) as empty.
• Jewel(J) as null, stones(S) as null.
• Jewel(J) as empty, stones(S) as empty.