There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results.
Example:
Input: n=3, str[]={"def","de","fgh"},q=3,queries={"de","lmn","fgh"}
Output: 1
0
1
Approach
Java
import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Stack;public class SparseArrays {public static void main(String[] args) {String[] str = { "def", "de", "fgh" };String[] queries = { "de", "lmn", "fgh" };int[] res = matchingStrings(str, queries);System.out.println(Arrays.toString(res));}private static int[] matchingStrings(String[] str, String[] queries) {HashMap<String, Integer> ump = new HashMap<String, Integer>();int q = queries.length;for (String s : str) {ump.put(s, ump.getOrDefault(s, 0) + 1);}List<Integer> v = new Stack<Integer>();for (int i = 0; i < q; i++) {if (!ump.containsKey(queries[i]))v.add(0);elsev.add(ump.get(queries[i]));}return v.stream().mapToInt(Integer::intValue).toArray();}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> matchingStrings(vector<string> strings, vector<string> queries){unordered_map<string, int> ump;int n = strings.size();int q = queries.size();for (int i = 0; i < n; i++){ump[strings[i]]++;}vector<int> v;for (int i = 0; i < q; i++){if (ump.find(queries[i]) == ump.end())v.push_back(0);elsev.push_back(ump[queries[i]]);}return v;}int main(){int n = 3;vector<string> str = {"def", "de", "fgh"};int q = 3;vector<string> queries = {"de", "lmn", "fgh"};vector<int> res = matchingStrings(str, queries);for (int i = 0; i < res.size(); i++){cout << res[i] << "\n";}return 0;}
No comments:
Post a Comment