问题链接:https://leetcode.com/problems/word-subsets/
这个题目其实比LeetCode--392. Is Subsequence还简单,感觉很水,想不到什么实际应用场景。贴上我低效的代码:
class Solution {
public static HashSet<String> set;
public static List<String> wordSubsets(String[] A, String[] B) {
LinkedList<String> ret=new LinkedList<>();
int[][] record1=new int[A.length][26];
set=new HashSet<>();
for(int i=0;i<A.length;i++)
{
for(int j=0;j<A[i].length();j++)
{
record1[i][A[i].charAt(j)-'a']+=1;
}
}
int[][] record2=new int[B.length][26];
for(int i=0;i<B.length;i++)
{
for(int j=0;j<B[i].length();j++)
{
record2[i][B[i].charAt(j)-'a']+=1;
}
}
for(int i=0;i<A.length;i++)
{
if(isSubset(record2,record1[i]) && !set.contains(A[i]))
{
ret.add(A[i]);
set.add(A[i]);
}
}
return ret;
}
public static boolean isSubset(int[][] record2,int[] longStr)
{
for(int i=0;i<record2.length;i++)
{
for(int j=0;j<26;j++)
{
if(record2[i][j]>longStr[j])
return false;
}
}
return true;
}
}
没有比较就没有伤害,那就用优秀的解法来自我伤害!
class Solution {
public List<String> wordSubsets(String[] A, String[] B) {
int[] bmax = count("");
for (String b: B) {
int[] bCount = count(b);
for (int i = 0; i < 26; ++i)
bmax[i] = Math.max(bmax[i], bCount[i]);
}
List<String> ans = new ArrayList();
search: for (String a: A) {
int[] aCount = count(a);
for (int i = 0; i < 26; ++i)
if (aCount[i] < bmax[i])
continue search;
ans.add(a);
}
return ans;
}
public int[] count(String S) {
int[] ans = new int[26];
for (char c: S.toCharArray())
ans[c - 'a']++;
return ans;
}
}