题目
 
解题
参考:
并查集
概念及应用

优化(路径压缩)
     按秩合并可以参考:「手画图解」手写UnionFind,并查集 不再畏惧 
代码
 
var equationsPossible = function(equations) {
const parent = new Array(26);
for (let i = 0; i < 26; i++) parent[i] = i;
const codeOfA = 'a'.charCodeAt();
for (const str of equations) {
if (str.charAt(1) === '=') {
const index1 = str.charCodeAt(0) - codeOfA;
const index2 = str.charCodeAt(3) - codeOfA;
union(parent, index1, index2);
}
}
for (const str of equations) {
if (str.charAt(1) === '!') {
const index1 = str.charCodeAt(0) - codeOfA;
const index2 = str.charCodeAt(3) - codeOfA;
if (find(parent, index1) === find(parent, index2)) {
return false;
}
}
}
return true;
};
const union = (parent, index1, index2) => {
parent[find(parent, index1)] = find(parent, index2);
};
const find = (parent, index) => {
while (parent[index] !== index) {
parent[index] = parent[parent[index]];
index = parent[index];
}
return index;
};

|