916. Word Subsets
We are given two arrays A and B of words. Each word is a string of lowercase letters.
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, “wrr” is a subset of “warrior”, but is not a subset of “world”.
Now say a word a from A is universal if for every b in B, b is a subset of a.
Return a list of all universal words in A. You can return the words in any order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { bool chk (unordered_map<char , int >& a, unordered_map<char ,int >& b) { for (auto entity : b) { if (a[entity.first] < entity.second) return false ; } return true ; } public : vector<string> wordSubsets (vector<string>& A, vector<string>& B) { int bsz = B.size (); vector<string> res; unordered_map<char , int > bMap; for (int i = 0 ; i < bsz; i++) { unordered_map<char ,int > m; for (int j = 0 ; j < B[i].length (); j++) m[B[i][j]]++; for (auto entity : m) { bMap[entity.first] = max (bMap[entity.first], entity.second); } } for (string& a : A) { unordered_map<char ,int > m; for (int i = 0 ; i < a.length (); i++) m[a[i]]++; if (chk (m, bMap)) res.push_back (a); } return res; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution { public List<String> wordSubsets (String[] A, String[] B) { Map<Character, Integer> bMap = new HashMap <>(); for (String b : B) { bMap = Stream.concat(bMap.entrySet().stream(), b.chars().boxed().collect(Collectors.toMap(k -> (char ) k.intValue(), v -> 1 , Integer::sum)) .entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1 > v2 ? v1 : v2, HashMap::new )); } Map<Character, Integer> finalBMap = bMap; return Arrays.asList(A).parallelStream().filter( a -> { Map<Character, Integer> aMap = a.chars().boxed().collect(Collectors.toMap(k -> (char ) k.intValue(), v -> 1 , Integer::sum)); for (Map.Entry<Character, Integer> entry : finalBMap.entrySet()) { if (aMap.getOrDefault(entry.getKey(), 0 ) < entry.getValue()) return false ; } return true ; } ).collect(Collectors.toList()); } }