Gemstones

There is a collection of rocks where each rock has various minerals embedded in it. Each type of mineral is designated by a lowercase letter in the range ascii[a-z]. There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in the collection.

Given a list of minerals embedded in each of the rocks, display the number of types of gemstones in the collection.


Example:

Input:  n=3,str[]={"abcdde","bacc","eeabg"}
Output: 2

Approach

Java

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Gemstones {
    public static void main(String[] args) {
        String[] str = { "abcdde""bacc""eeabg" };
        System.out.println(gemstones(str));
    }

    static int gemstones(String[] str) {
        int n = str.length;
        HashSet<Characterst = new HashSet<Character>();
        List<Characterres = new ArrayList<Character>();
        for (int i = 0; i < str[0].length(); i++) {
            st.add(str[0].charAt(i));
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < str[i].length(); j++) {
                if (st.contains(str[i].charAt(j))) {
                    res.add(str[i].charAt(j));
                }
            }
            st=new HashSet<Character>();
            for (int k = 0; k < res.size(); k++)
                st.add(res.get(k));
            res.clear();
        }
        return st.size();
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int gemstones(vector<stringstr)
{

    int n = str.size();
    set<charst;
    vector<charres;
    for (int i = 0i < str[0].size(); i++)
        st.insert(str[0][i]);
    for (int i = 1i < ni++)
    {
        for (int j = 0j < str[i].size(); j++)
        {
            if (st.find(str[i][j]!= st.end())
            {
                res.push_back(str[i][j]);
            }
        }
        st.clear();
        for (int k = 0k < res.size(); k++)
            st.insert(res[k]);
        res.clear();
    }
    return st.size();
}

int main()
{
    int n = 3;

    vector<stringstr = {"abcdde""bacc""eeabg"};
    cout << gemstones(str);
    return 0;
}


No comments:

Post a Comment