1 | 给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。 |
并查集
初始化并查集,union每个等式中的两个字母
遍历等式数组,查找每个字母的根节点fa,fb
- $fa==fb$ but $op$ is $!=$ result false
- $fa !=fb$ but $op$ is $==$ result false
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
52class Solution {
public boolean equationsPossible(String[] equations) {
//fa==fb but op is != is false
//fa!=fb but op is == is false
for (int i = 0; i < 26; i++) {
father[i] = i;
}
for (int i = 0; i < equations.length; i++) {
int op1 = equations[i].charAt(0) - 'a';
char op = equations[i].charAt(1);
int op2 = equations[i].charAt(3) - 'a';
if (op == '=') union(op1, op2);
}
for (int i = 0; i < equations.length; i++) {
int op1 = equations[i].charAt(0) - 'a';
char op = equations[i].charAt(1);
int op2 = equations[i].charAt(3) - 'a';
int fa = find(op1);
int fb = find(op2);
if ((op == '=' && fa != fb) || (op == '!' && fa == fb)) {
return false;
}
}
return true;
}
int[] father = new int[26];
public int find(int x) {
int a = x;
// 寻找根节点
while (x != father[x]) x = father[x];
// x就是根节点
// 找到根节点后,把当前路径上的所有元素的根节点都改成x
while (a != father[a]) {
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
public void union(int a, int b) {
int fa = find(a);
int fb = find(b);
if (fa != fb) father[fa] = fb;
}
}