-
Notifications
You must be signed in to change notification settings - Fork 0
/
후보키.java
61 lines (44 loc) · 1.59 KB
/
후보키.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.HashSet;
import java.util.Set;
class Solution {
public static Set<Integer> candidateKeys = new HashSet<>();
public int solution(String[][] relation) {
int columnSize = relation[0].length;
for (int state = 0; state < (1 << columnSize); ++state) {
boolean superKey = false;
Set<String> rows = new HashSet<>();
for (String[] row : relation) {
int nowState = state;
StringBuilder nowRow = new StringBuilder();
for (int i = 0; i < columnSize; ++i) {
int used = nowState % 2;
if (used == 1) {
nowRow.append(row[i]);
}
nowState /= 2;
}
String target = nowRow.toString();
if (target.isEmpty() || rows.contains(target)) {
break;
}
rows.add(target);
}
if (rows.size() == relation.length) {
for (Integer candidateKey : candidateKeys) {
if (isSuperKey(state,candidateKey)) {
superKey = true;
break;
}
}
if (!superKey) {
candidateKeys.add(state);
}
}
}
return candidateKeys.size();
}
public boolean isSuperKey(Integer key, Integer candidateKey) {
int commonValue = key & candidateKey;
return commonValue > 0 && (commonValue == candidateKey);
}
}