-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.java
34 lines (31 loc) · 1.03 KB
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<String> wordSubsets(String[] words1, String[] words2) {
int[] maxFreq = new int[26];
// Precompute the maximum frequency for each character in words2
for (String word : words2) {
int[] freq = new int[26];
for (char c : word.toCharArray())
freq[c - 'a']++;
for (int i = 0; i < 26; i++) {
maxFreq[i] = Math.max(maxFreq[i], freq[i]);
}
}
List<String> result = new ArrayList<>();
// Check each word in words1
for (String word : words1) {
int[] freq = new int[26];
for (char c : word.toCharArray())
freq[c - 'a']++;
boolean isUniversal = true;
for (int i = 0; i < 26; i++) {
if (freq[i] < maxFreq[i]) {
isUniversal = false;
break;
}
}
if (isUniversal)
result.add(word);
}
return result;
}
}