力扣本题传送门
这道题,按照助教的代码撸一遍,并查集是直接复制的来的,最近几道题都是用到并查集,但是我并不是恨离基
/*
* @lc app=leetcode.cn id=990 lang=javascript
*
* [
*/
// @lc code=start
/**
* @param {string[]} equations
* @return {boolean}
*/
class UnionFind {
constructor(n) {
this.parent = new Array(n).fill(0).map((value, index) => index);
this.rank = new Array(n).fill(1);
this.setCount = n;
}
findSet(index) {
if (this.parent[index] != index) {
this.parent[index] = this.findSet(this.parent[index])
}
return this.parent[index]
}
unite(index1, index2) {
let root1 = this.findSet(index1), root2 = this.findSet(index2);
if (root1 !== root2) {
// 这一步不离基
// 就是把节点少的往节点多的合并
if (root1 < root2) {
[root1, root2] = [root2, root1]
}
// 合并 这一步明白
this.parent[root2] = root1;
// 计算合并的疏朗
this.rank[root1] += this.rank[root2];
//合并以后减少
this.setCount--;
}
}
getCount() {
return this.setCount;
}
// 判断两个节点是否联通 就是看他们的根节点是否相同
connected(index1, index2) {
let root1 = this.findSet(index1), root2 = this.findSet(index2);
return root1 === root2;
}
}
// 小写z的ASCII=97
var equationsPossible = function (equations) {
let size = equations.length;
let uf = new UnionFind(26);
// 第一次扫描
for (const str of equations) {
if (str.charAt(1) === '=') {
uf.unite(str.charCodeAt(0) - 97, str.charCodeAt(3) - 97)
}
}
// 第二次扫描
for (const str of equations) {
if (str.charAt(1) === '!') {
if (uf.connected(str.charCodeAt(0) - 97, str.charCodeAt(3) - 97)) {
return false;
}
}
}
return true;
};
// @lc code=end