Jewels and Stones

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.

METHOD 1:

class Solution {
    public int numJewelsInStones(String J, String S) {
       int res=0;
       for(char c : S.toCharArray()){
           if(J.indexOf(c) != -1){
               res++;
           }
       }
       return res;
    }
}

Try it on Leetcode

Here, in the problem they mention that J string has unique characters. So, we are traversing each character from S string and if we found index of that character in J string [i.e., whatever the index we can end up that character is present in J string, if that character is not found, it will be -1] , then increase the result by 1. Finally return the result.


METHOD 2:


class Solution {
    public int numJewelsInStones(String J, String S) {
        int len = S.length(), len1=J.length();
        for(int i=0;i<len1;i++)
        {
            S = S.replaceAll(J.charAt(i)+"","");
        }
        return len-S.length();
    }
}



Try it on Leetcode

Here, we are going to traverse J string. For each character found in S string, we are removing multiple occurrence of those characters from S string. Finally, subtraction of total length and current S string length will be the result.


Below image runtime and memory comparison of both methods.
First row accepted solution is METHOD 1
Second row accepted solution is METHOD 2


Runtime and Memory comparison


Related Posts:

Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation


Please let us know your views in comment section

Subscribe us to receive updates instantly..

Happy Coding..!!
  

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II