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<Character> st = new HashSet<Character>();List<Character> res = 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<string> str){int n = str.size();set<char> st;vector<char> res;for (int i = 0; i < str[0].size(); i++)st.insert(str[0][i]);for (int i = 1; i < n; i++){for (int j = 0; j < str[i].size(); j++){if (st.find(str[i][j]) != st.end()){res.push_back(str[i][j]);}}st.clear();for (int k = 0; k < res.size(); k++)st.insert(res[k]);res.clear();}return st.size();}int main(){int n = 3;vector<string> str = {"abcdde", "bacc", "eeabg"};cout << gemstones(str);return 0;}
No comments:
Post a Comment