Articles by Victoria

LeetCode Challenge #3: Jewels and Stones

May 22, 20200 min read
cover

Problem Statement

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

Step by Step Solution

Identify patterns After reading the problem and examples, we can conclude 3 things:

  1. The output of this problem is an integer that represents how many characters of String J exist in String S.
  2. We have to compare each character (char) of J to each character (char) of S.
  3. If character of J is found in S, we increase the output count by 1.

Write the Pseudocode The following solution can be written as:

  1. Initialize the output integer count to 0.
  2. Have a for loop that iterates through String S.
  3. Inside that for loop, have a for loop that iterates through String J. If char at S[i] == char at J[j], increase count by 1. Else, move onto the next index.
  4. Finally, after the outer for loop finishes, return the count output.

Remember: We want to check if a char of J is found in each char of S. So for example, when the outer for loop is at S[0], we will have the inner for loop iterate through J[0] to J[length-1] to check if S[0] == J[j]. If there is, increase the count variable by 1. Else, do nothing. Then, the outer for loop will move onto S[1] and the inner for loop will again check if J[0] to J[length-1] matches S[1] and so on. The loop stops after it reaches the final character of S.

Let's get coding! Now, let's try to put the pseudocode into Java:

class Solution {
    public int numJewelsInStones(String J, String S) {

        //Initialize count
        int count = 0;

        for(int i=0; i< S.length(); i++){
            for(int j=0; j<J.length(); j++){
                if(S.charAt(i) == J.charAt(j)){ //check if there's a match
                    count++;
                    break;
                }
            }
        }
        return count;
    }
}

Conclusion

This problem may seem difficult to understand for beginners but once you have a clear understanding about strings and for loops, it is definitely not a hard problem. I hope I explained it clear enough but feel free to ask any clarifying questions on my profile here. Keep practicing and good luck to anyone who's challenging LeetCode too!

More from LeetCode Challenge

View full series →

More Articles