-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathWordsSubset.java
42 lines (34 loc) · 1018 Bytes
/
WordsSubset.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
35
36
37
38
39
40
41
42
class Solution {
public List<String> wordSubsets(String[] A, String[] B) {
List<String> ans = new ArrayList<>();
int[] maxFreqAcrossB = new int[26];
for(String bStr : B){
int[] freqCountBStr = freq(bStr);
for(int i=0;i<26;i++){
maxFreqAcrossB[i] = Math.max(maxFreqAcrossB[i], freqCountBStr[i]);
}
}
for(String aStr: A){
int[] freqCountAStr =freq(aStr);
boolean foundAllChar = true;
for(int i=0;i<26;i++){
if(freqCountAStr[i] < maxFreqAcrossB[i]){
foundAllChar = false;
break;
}
}
if(foundAllChar){
ans.add(aStr);
}
}
return ans;
}
// O(len(s))
private int[] freq(String s){
int[] freqCount = new int[26];
for(char c: s.toCharArray()){
freqCount[c-'a']++;
}
return freqCount;
}
}