题目描述
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
解题思路
算法,数据结构
并查集,根据等式,记录相等节点的联通情况
过程
首先遍历所有的等式,在并查集中记录,eg:a === b,那么 a 和 b 是联通的
然后遍历所有的不等式,如果不想等,但是并查集中记录的情况是二者联通,那么直接 return false
代码
/**
* @param {string[]} equations
* @return {boolean}
*/
var equationsPossible = function (equations) {
const u = new UnionSet(26)
for (const item of equations) {
const c1 = item[0].charCodeAt() - 97
const c2 = item[3].charCodeAt() - 97
const mark = item[1]
if (mark === "=") u.merge(c1, c2)
}
for (const item of equations) {
const c1 = item[0].charCodeAt() - 97
const c2 = item[3].charCodeAt() - 97
const mark = item[1]
if (mark === "!" && u.get(c1) === u.get(c2)) return false
}
return true
}
class UnionSet {
constructor(n) {
this.fa = new Array(n).fill(0).map((item, index) => index)
}
get(x) {
return (this.fa[x] = this.fa[x] === x ? x : this.get(this.fa[x]))
}
merge(a, b) {
this.fa[this.get(a)] = this.get(b)
}
}