990. Satisfiability of Equality Equations
Solution
Key: 2 times parsing, one for '==' another for checking '!='
public boolean equationsPossible(String[] equations) {
int[] map = new int[26];
for(int i = 0; i < 26; i++){
map[i] = i;
}
for(String eq : equations){
if(eq.charAt(1) == '='){
union(map, eq.charAt(0), eq.charAt(3));
}
}
for(String eq : equations){
if(eq.charAt(1) == '!')
{
int aRoot = find(map, eq.charAt(0) - 'a');
int bRoot = find(map, eq.charAt(3) - 'a');
if(aRoot == bRoot) return false;
}
}
return true;
}
public int find(int[] map, int c){
if(map[c] != c){
map[c] = find(map, map[c]);
}
return map[c];
}
public void union(int[] map, char a, char b){
int aRoot = find(map, a-'a');
int bRoot = find(map, b-'a');
map[bRoot] = aRoot;
}
Last updated
Was this helpful?