forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
40 lines (36 loc) · 1.11 KB
/
Solution.ts
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
class UnionFind {
private parent: number[];
constructor() {
this.parent = Array.from({ length: 26 }).map((_, i) => i);
}
find(index: number) {
if (this.parent[index] === index) {
return index;
}
this.parent[index] = this.find(this.parent[index]);
return this.parent[index];
}
union(index1: number, index2: number) {
this.parent[this.find(index1)] = this.find(index2);
}
}
function equationsPossible(equations: string[]): boolean {
const uf = new UnionFind();
for (const [a, s, _, b] of equations) {
if (s === '=') {
const index1 = a.charCodeAt(0) - 'a'.charCodeAt(0);
const index2 = b.charCodeAt(0) - 'a'.charCodeAt(0);
uf.union(index1, index2);
}
}
for (const [a, s, _, b] of equations) {
if (s === '!') {
const index1 = a.charCodeAt(0) - 'a'.charCodeAt(0);
const index2 = b.charCodeAt(0) - 'a'.charCodeAt(0);
if (uf.find(index1) === uf.find(index2)) {
return false;
}
}
}
return true;
}