给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
示例 1:
输入:["a==b","b!=a"]
输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
示例 2:
输入:["b==a","a==b"]
输出:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
示例 3:
输入:["a==b","b==c","a==c"]
输出:true
示例 4:
输入:["a==b","b!=c","c==a"]
输出:false
示例 5:
输入:["c==c","b==d","x!=z"]
输出:true
提示:
1 <= equations.length <= 500 equations[i].length == 4 equations[i][0] 和 equations[i][3] 是小写字母 equations[i][1] 要么是 '=',要么是 '!' equations[i][2] 是 '='
解题思路 该题目可以使用并查集相关思想,并查集是处理连通性问题的一种解决方案,该题可以模拟a,b,c作为点,a==b,b==c相当于a连通b,b连通c,即三者处于一个集合中。当后续若出现b!=c,则相当于找并查集中两个点的父节点,若相同,则说明a==b,处于一个集合,与b!=c冲突,返回false
代码
/**
* @param {string[]} equations
* @return {boolean}
*/
var equationsPossible = function (equations) {
const set = new UnionSet(26)
for (let i = 0; i < equations.length; i++) {
if (equations[i][1] == '!') continue;
const a = equations[i][0].charCodeAt() - 'a'.charCodeAt();
const b = equations[i][3].charCodeAt() - 'a'.charCodeAt();
set.merge(a, b)
}
for (let i = 0; i < equations.length; i++) {
if (equations[i][1] == '=') continue;
const a = equations[i][0].charCodeAt() - 'a'.charCodeAt();
const b = equations[i][3].charCodeAt() - 'a'.charCodeAt();
if (set.find(a) === set.find(b)) return false
}
return true
};
var UnionSet = function (n) {
this.fathers = new Array(n);
this.size = new Array(n)
for (let i = 0; i < n; i++) {
this.fathers[i] = i
this.size[i] = 1
}
}
UnionSet.prototype.find = function (x) {
if (this.fathers[x] === x) return x;
return this.find(this.fathers[x])
}
UnionSet.prototype.merge = function (a, b) {
const fa = this.find(a), fb = this.find(b);
if (fa === fb) return;
if (this.size[fa] < this.size[fb]) {
this.fathers[fa] = fb
this.size[fb] += this.size[fa]
} else {
this.fathers[fb] = fa
this.size[fa] += this.size[fb]
}
}