题目描述:
我们给出两个单词数组 A 和 B。每个单词都是一串小写字母。
现在,如果 b 中的每个字母都出现在 a 中,包括重复出现的字母,那么称单词 b 是单词 a 的子集。 例如,“wrr” 是 “warrior” 的子集,但不是 “world” 的子集。
如果对 B 中的每一个单词 b,b 都是 a 的子集,那么我们称 A 中的单词 a 是通用的。
你可以按任意顺序以列表形式返回 A 中所有的通用单词。
示例 1:
输入:A = [“amazon”,“apple”,“facebook”,“google”,“leetcode”], B = [“e”,“o”]
输出:[“facebook”,“google”,“leetcode”]
示例 2:
输入:A = [“amazon”,“apple”,“facebook”,“google”,“leetcode”], B = [“l”,“e”]
输出:[“apple”,“google”,“leetcode”]
示例 3:
输入:A = [“amazon”,“apple”,“facebook”,“google”,“leetcode”], B = [“e”,“oo”]
输出:[“facebook”,“google”]
示例 4:
输入:A = [“amazon”,“apple”,“facebook”,“google”,“leetcode”], B = [“lo”,“eo”]
输出:[“google”,“leetcode”]
示例 5:
输入:A = [“amazon”,“apple”,“facebook”,“google”,“leetcode”], B = [“ec”,“oc”,“ceo”]
输出:[“facebook”,“leetcode”]
提示:
1 <= A.length, B.length <= 10000
1 <= A[i].length, B[i].length <= 10
A[i] 和 B[i] 只由小写字母组成。
A[i] 中所有的单词都是独一无二的,也就是说不存在 i != j 使得 A[i] == A[j]。
很显然,如果直接使用暴力法是肯定会超时的,因此可以考虑将给出的字符串数组B进行简单的处理,根据题目意思我们可以知道,就是B中所有出现的单词,如果某一个字符串出现多个以最多的计数,即不累加,接着将A进行处理,放入temA中,是一个二维数组,接着进行遍历
代码如下:
class Solution {
public List<String> wordSubsets(String[] A, String[] B) {
List<String> result = new ArrayList<>();
int [][] temA = new int[A.length][26];
int [][] temB = new int[B.length][26];
int table[] = new int[26];
//将B中的单词全部放入temB中
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B[i].length(); j++) {
temB[i][B[i].charAt(j) - 'a'] ++;
}
for (int j = 0; j < table.length; j++) {
if(table[j]<temB[i][j]){
table[j] = temB[i][j];
}
}
}
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length(); j++) {
temA[i][A[i].charAt(j) - 'a']++;
}
}
for (int i = 0; i < A.length; i++) {
boolean flag = true;
for (int j = 0; j < 26; j++) {
if(table[j] > temA[i][j]){
flag = false;
break;
}
}
if(flag){
result.add(A[i]);
}
}
return result;
}
}
排名比较靠前了
排名靠前的代码
class Solution {
public List<String> wordSubsets(String[] A, String[] B) {
List<String> list = new ArrayList<String>();
final int maxn = 26;
int need[] = new int[maxn];
int tmp[] = new int[maxn];
for(int i=0;i<B.length;i++)
{
for(int j=0;j<B[i].length();j++)
{
tmp[B[i].charAt(j)-'a'] ++;
}
for(int j=0;j<maxn;j++)
{
if(need[j]<tmp[j]) need[j] = tmp[j];
tmp[j] = 0;
}
}
for(int i=0;i<A.length;i++)
{
boolean f = true;
for(int j=0;j<A[i].length();j++)
{
tmp[A[i].charAt(j)-'a']++;
}
for(int j=0;j<maxn;j++)
{
if(tmp[j]<need[j]) {
f = false;
}
tmp[j] = 0;
}
if(f) list.add(A[i]);
}
return list;
}
}