-
Notifications
You must be signed in to change notification settings - Fork 1
/
WordSubsets.java
47 lines (40 loc) · 1.17 KB
/
WordSubsets.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
43
44
45
46
47
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/word-subsets/
public class WordSubsets {
private final String[] words1;
private final String[] words2;
public WordSubsets(String[] words1, String[] words2) {
this.words1 = words1;
this.words2 = words2;
}
public List<String> solution() {
int[] bMax = count("");
for (String b : words2) {
int[] bCount = count(b);
for (int i = 0; i < 26; i++) {
bMax[i] = Math.max(bMax[i], bCount[i]);
}
}
List<String> result = new ArrayList<>();
search:
for (String a : words1) {
int[] aCount = count(a);
for (int i = 0; i < 26; i++) {
if (aCount[i] < bMax[i]) {
continue search;
}
}
result.add(a);
}
return result;
}
public int[] count(String s) {
int[] result = new int[26];
for (int i = 0; i < s.length(); i++) {
result[s.charAt(i) - 'a']++;
}
return result;
}
}