0916. Word Subsets (M)

Word Subsets (M)

题目

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:

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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
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

class Solution {
    public List<String> wordSubsets(String[] A, String[] B) {
        List<String> ans = new ArrayList<>();
        int[] cnt = new int[26];

        for (String word : B) {
            int[] tmp = letterCount(word);
            for (int i = 0; i < 26; i++) {
                cnt[i] = Math.max(cnt[i], tmp[i]);
            }
        }

        for (String word : A) {
            int[] tmp = letterCount(word);
            boolean valid = true;

            for (int i = 0; i < 26; i++) {
                if (cnt[i] > 0 && cnt[i] > tmp[i]) {
                    valid = false;
                    break;
                }
            }
            
            if (valid) ans.add(word);
        }

        return ans;
    }

    private int[] letterCount(String word) {
        int[] tmp = new int[26];
        for (char c : word.toCharArray()) {
            tmp[c - 'a']++;
        }
        return tmp;
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/14583231.html