990. Satisfiability of Equality Equations

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
class Solution {
private static class UnionFind {
private final int[] parent;

public UnionFind(int count) {
this.parent = new int[count];
for (int i = 0; i < count; i++) {
this.parent[i] = i;
}
}

public void union(int x, int y) {
int xRoot = getRoot(x);
int yRoot = getRoot(y);
if (xRoot == yRoot) {
return;
}

parent[xRoot] = yRoot;
}

public int getRoot(int x) {
while (x != parent[x]) {
parent[x] = parent[parent[x]]; // path compression
x = parent[x];
}

return x;
}

public boolean isConnected(int x, int y) {
return getRoot(x) == getRoot(y);
}
}

public boolean equationsPossible(String[] equations) {
UnionFind unionFind = new UnionFind(26);

for (String equation : equations) {
if (equation.charAt(1) == '=') {
int x = equation.charAt(0) - 'a';
int y = equation.charAt(3) - 'a';
unionFind.union(x, y);
}
}

for (String equation : equations) {
if (equation.charAt(1) == '!') {
int x = equation.charAt(0) - 'a';
int y = equation.charAt(3) - 'a';
if (unionFind.isConnected(x, y)) {
return false;
}
}
}

return true;
}
}

References

990. Satisfiability of Equality Equations
使用并查集处理不相交集合问题(Java、Python)