Find how many of the stones you have are also jewels.
Example:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Approach
Java
import java.util.HashMap;public class JewelsAndStones {public static void main(String[] args) {String jewels = "aA";String stones = "aAAbbbb";int n = numJewelsInStones(jewels, stones);System.out.println(n);}// function to find the number// of stones and jewelsstatic int numJewelsInStones(String j, String s) {int sum = 0;// create map to hold frequencyHashMap<Character, Integer> mapS = new HashMap<>();// iterate till end of sfor (int i = 0; i < s.length(); i++) {// set frequency of stringmapS.put(s.charAt(i), mapS.getOrDefault(s.charAt(i), 0) + 1);}// sum of jewels latter frequencyfor (int i = 0; i < j.length(); i++) {sum += mapS.getOrDefault(j.charAt(i),0);}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the number//of stones and jewelsint numJewelsInStones(string J, string S){int n=J.size();int m=S.size();int f1[26]={0};int f2[26]={0};for(int i=0;i<n;i++){if(J[i]>='A'&&J[i]<='Z')f1[J[i]-'A']++;elsef2[J[i]-'a']++;}int f3[26]={0};int f4[26]={0};for(int i=0;i<m;i++){if(S[i]>='A'&&S[i]<='Z')f3[S[i]-'A']++;elsef4[S[i]-'a']++;}int sum=0;for(int i=0;i<26;i++){if(f1[i]>0)sum+=f3[i];if(f2[i]>0)sum+=f4[i];}return sum;}int main(){string jewels = "aA";string stones = "aAAbbbb";cout<<numJewelsInStones(jewels,stones);return 0;}
No comments:
Post a Comment