forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSatisfiability of Equality Equations.java
65 lines (61 loc) · 1.6 KB
/
Satisfiability of Equality Equations.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
62
63
64
65
class Solution {
private class UF{
int count;
int[] parent;
public UF(int n){
count = n;
parent = new int[n];
for(int i = 0; i < n; i++){
parent[i] = i;
}
}
public int find(int x){
if(parent[x] != x){
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int a, int b){
int rootA = find(a);
int rootB = find(b);
if(rootA == rootB){
return;
}
parent[rootA] = rootB;
count --;
}
public boolean connected(int a, int b){
int rootA = find(a);
int rootB = find(b);
if(rootA == rootB){
return true;
}else{
return false;
}
}
}
public boolean equationsPossible(String[] equations) {
UF uf = new UF(26);
int count = 0;
for(String s : equations){
if(s.charAt(1) == '='){
uf.union(s.charAt(0) - 'a', s.charAt(3) - 'a');
}else{
equations[count] = s;
count++;
}
}
for(String s : equations){
count --;
if(count < 0){
break;
}
if(s.charAt(1) == '!'){
if(uf.connected(s.charAt(0) - 'a', s.charAt(3) - 'a')){
return false;
}
}
}
return true;
}
}