class Solution {
public boolean equationsPossible(String[] equations) {
int n = equations.length;
//String[] noequal = new String[n];
UnionFind uf = new UnionFind(26);
for(int i = 0;i < n;i++){
char c1 = equations[i].charAt(0);
char c2 = equations[i].charAt(3);
int index1 = c1-'a';
int index2 = c2-'a';
if(equations[i].charAt(1) == '=')
uf.union(index1,index2);
}
for(int i = 0;i < n;i++){
char c1 = equations[i].charAt(0);
char c2 = equations[i].charAt(3);
int index1 = c1-'a';
int index2 = c2-'a';
if(equations[i].charAt(1) == '!'){
if(uf.find(index1) == uf.find(index2))
return false;
}
}
return true;
}
public class UnionFind{
int[] parent;
int[] rank;
int count;
public int getCount(){
return count;
}
public UnionFind(int n){
parent = new int[n];
rank = new int[n];
count = n;
for(int i = 0;i < n;i++){
parent[i] = i;
rank[i] = 1;
}
}
public int find(int x){
if(parent[x] != x){
parent[x] = find(parent[x]);
}
return parent[x];
}
public boolean union(int x,int y){
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY)
return false;
if(rank[rootX] == rank[rootY]){
parent[rootX] = rootY;
rank[rootY] += 1;
}
else if(rank[rootX] > rank[rootY]){
parent[rootY] = rootX;
}
else{
parent[rootX] = rootY;
}
count -= 1;
return true;
}
}
}