链接:https://leetcode-cn.com/problems/word-subsets/
将B中的单词整合为一个大单词记录A中单词的字幕出现频率,与大单词进行比较即可。
java代码:
class Solution {
public List<String> wordSubsets(String[] A, String[] B) {
List<String> ans = new ArrayList();
int []alphbetsinB = new int [26];//将B合成一个单词
for(int i = 0;i<B.length;i++)
{
int [] temp = new int [26];
for(int j = 0;j<B[i].length();j++)
temp[B[i].charAt(j)-'a']++;
for(int k = 0;k<26;k++) //更新B中字母出现最大次数
alphbetsinB[k] = Math.max(temp[k],alphbetsinB[k]);
}
for(int i = 0;i<A.length;i++)
{
int []alphbetsinA = new int [26];
for(int j = 0;j<A[i].length();j++) //统计字母出现次数
alphbetsinA[A[i].charAt(j)-'a']++;
for(int k = 0;k<26;k++) //与B进行比较
{
if(alphbetsinA[k]<alphbetsinB[k])
break;
if(k==25)
ans.add(A[i]);
}
}
return ans;
}
}