990. Satisfiability of Equality Equations 发表于 2022-09-21 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859class Solution { private static class UnionFind { private final int[] parent; public UnionFind(int count) { this.parent = new int[count]; for (int i = 0; i < count; i++) { this.parent[i] = i; } } public void union(int x, int y) { int xRoot = getRoot(x); int yRoot = getRoot(y); if (xRoot == yRoot) { return; } parent[xRoot] = yRoot; } public int getRoot(int x) { while (x != parent[x]) { parent[x] = parent[parent[x]]; // path compression x = parent[x]; } return x; } public boolean isConnected(int x, int y) { return getRoot(x) == getRoot(y); } } public boolean equationsPossible(String[] equations) { UnionFind unionFind = new UnionFind(26); for (String equation : equations) { if (equation.charAt(1) == '=') { int x = equation.charAt(0) - 'a'; int y = equation.charAt(3) - 'a'; unionFind.union(x, y); } } for (String equation : equations) { if (equation.charAt(1) == '!') { int x = equation.charAt(0) - 'a'; int y = equation.charAt(3) - 'a'; if (unionFind.isConnected(x, y)) { return false; } } } return true; }} Reference990. Satisfiability of Equality Equations使用并查集处理不相交集合问题(Java、Python)