LeetCode-Word Subsets

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83312008

一、Description

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 aincluding 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 Bb is a subset of a

Return a list of all universal words in A.  You can return the words in any order.

题目大意:

有两个字符串数组A和B,数组中的每个字符串都是小写字母组成的,将所有A中包含B中所有字符串的字母组合的字符串返回,返回的字符串顺序可以任意。其中假如B中有一个串为"wrr",则"warrior"包含该串的所有字母,但"world"不包含,因为重复的字母也要算。

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"]

二、Analyzation

这个题比较麻烦,提交了很多次,都有些问题,通过借鉴discuss中的一些方法,按照自己的理解AC了。遍历B中的字符串,并对每个字符串中的字母进行统计,放在alp数组中,不同的字符串alp数组不同(每个字符串的字母出现次数不同),但把字母表中出现次数最多的保留在count数组中,然后遍历A,只要A中哪个字符串中的字母出现次数大于等于count数组中对应字母的次数,就加入到列表中,最后返回列表即可。


三、Accepted code

class Solution {
    public List<String> wordSubsets(String[] A, String[] B) {
        List<String> list = new ArrayList<>();
        if (A == null || A.length == 0) {
            return list;
        }
        int[] count = new int[26];
        for (String s : B) {
            char[] b = new char[26];
            for (int i = 0; i < s.length(); i++) {
                int tmp = s.charAt(i) - 'a';
                b[tmp]++;
                count[tmp] = Math.max(count[tmp], b[tmp]);
            }
        }
        boolean flag = true;
        for (String s : A) {
            flag = true;
            char[] a = new char[26];
            for (int i = 0; i < s.length(); i++) {
                int tmp = s.charAt(i) - 'a';
                a[tmp]++;
            }
            for (int i = 0; i < 26; i++) {
                if (a[i] < count[i]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                list.add(s);
            }
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83312008