题目

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.

Example 1:

  1. Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
  2. Output: ["facebook","google","leetcode"]

Example 2:

  1. Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
  2. Output: ["apple","google","leetcode"]

Example 3:

  1. Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
  2. Output: ["facebook","google"]

Example 4:

  1. Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
  2. Output: ["google","leetcode"]

Example 5:

  1. Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
  2. Output: ["facebook","leetcode"]

Note:

  1. 1 <= A.length, B.length <= 10000
  2. 1 <= A[i].length, B[i].length <= 10
  3. A[i] and B[i] consist only of lowercase letters.
  4. All words in A[i] are unique: there isn’t i != j with A[i] == A[j].

题意

给定两个字符串数组A和B,要求从A中找出所有的字符串s,满足s包含B中每一个字符串的所有字符。

思路

对B进行预处理,将其转化成一个字符统计数组cnt,其中每个字符c的出现次数是c在B中各个字符串中出现次数的最大值,这样只要满足一个字符串s对应字符的出现次数大于cnt中各字符的出现次数,s就包含B中每一个字符串的所有字符。之后只要比较A中每个字符串和cnt数组即可。


代码实现

Java

  1. class Solution {
  2. public List<String> wordSubsets(String[] A, String[] B) {
  3. List<String> ans = new ArrayList<>();
  4. int[] cnt = new int[26];
  5. for (String word : B) {
  6. int[] tmp = letterCount(word);
  7. for (int i = 0; i < 26; i++) {
  8. cnt[i] = Math.max(cnt[i], tmp[i]);
  9. }
  10. }
  11. for (String word : A) {
  12. int[] tmp = letterCount(word);
  13. boolean valid = true;
  14. for (int i = 0; i < 26; i++) {
  15. if (cnt[i] > 0 && cnt[i] > tmp[i]) {
  16. valid = false;
  17. break;
  18. }
  19. }
  20. if (valid) ans.add(word);
  21. }
  22. return ans;
  23. }
  24. private int[] letterCount(String word) {
  25. int[] tmp = new int[26];
  26. for (char c : word.toCharArray()) {
  27. tmp[c - 'a']++;
  28. }
  29. return tmp;
  30. }
  31. }