-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution990.java
More file actions
51 lines (48 loc) · 1.54 KB
/
Copy pathSolution990.java
File metadata and controls
51 lines (48 loc) · 1.54 KB
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
class Solution990 {
private char[] parent = new char[26];
private int[] rank = new int[26];
public boolean equationsPossible(String[] equations) {
// 初始化并查集及其高度
for (int i = 0; i < 26; i++) {
char index = (char) ('a' + i);
parent[i] = index;
rank[i] = 1;
}
// 遍历数组,确定连通分量的数量
for (int i = 0; i < equations.length; i++) {
String temp = equations[i];
char x = temp.charAt(0), y = temp.charAt(3);
if (temp.charAt(1) == '=') {
// 这两个字母连通
union(x, y);
}
}
for (int i = 0; i < equations.length; i++) {
String temp = equations[i];
if (temp.charAt(1) != '=') {
if (find(temp.charAt(0)) == find(temp.charAt(3))) return false;
}
}
return true;
}
// 带路径压缩的查找
public char find(char c) {
if (parent[c - 'a'] != c) {
parent[c - 'a'] = find(parent[c - 'a']);
}
return parent[c - 'a'];
}
// 按秩合并
public void union(char x, char y) {
char xroot = find(x), yroot = find(y);
if (xroot != yroot) {
if (rank[xroot - 'a'] <= rank[yroot - 'a']) {
parent[xroot - 'a'] = yroot;
}
else {
parent[yroot - 'a'] = xroot;
}
if (rank[xroot - 'a'] == rank[yroot - 'a']) rank[yroot - 'a']++;
}
}
}