[路飞]leetcode-990.等式方程的可满足性

82 阅读1分钟

给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。

只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。 力扣原文

示例 1:

输入: ["a==b","b!=a"]
输出: false
解释: 如果我们指定,a = 1b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。

示例 2:

输入: ["b==a","a==b"]
输出: true
解释: 我们可以指定 a = 1b = 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

解题:

class UnionFind {
  constructor(length) {
    this.parent = new Array(length).fill(0).map((v, index) => index);
    this.rank = new Array(length).fill(1);
    this.setCount = length;
  }
  findSet(index) {
    if (this.parent[index] !== index) {
      this.parent[index] = this.findSet(this.parent[index]);
    }
    return this.parent[index];
  }
  unite(indei, index2) {
    let root1 = this.findSet(indei),
      root2 = this.findSet(index2);
    if (root1 !== root2) {
      if (this.rank[root1] < this.rank[root2]) {
        [root1, root2] = [root2, root1];
      }
      this.parent[root2] = root1;
      this.rank[root1] += this.rank[root2];
      this.setCount--;
    }
  }
  getCount() {
    return this.setCount;
  }
}

var equationsPossible = function (equations) {
  const uf = new UnionFind(26);
  for (const iterator of equations) {
    if (iterator[1] === "=") {
      uf.unite(iterator.charCodeAt(0) - 97, iterator.charCodeAt(3) - 97);
    }
  }
  for (const iterator of equations) {
    if (iterator[1] === "!") {
      if (
        uf.findSet(iterator.charCodeAt(0) - 97) ===
        uf.findSet(iterator.charCodeAt(3) - 97)
      ) {
        return false;
      }
    }
  }
  return true;
};