[路飞]_leetcode刷题_990. 等式方程的可满足性

178 阅读2分钟

题目:

990. 等式方程的可满足性

给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 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

解法一

思路:

并查集。

我们的目标是检验所有等式是否都成立,我们可以通过并查集,先处理相等的等式,将涉及到的变量做合并,然后再处理不等式,看看是否都能满足,如果有不满足的则为false,如果都满足则为true。

具体步骤如下:

  1. 先初始化parent数组,用26个小写字母的charCode去填充
  2. 遍历equations内的等式,将涉及到的变量合并
  3. 再遍历equations内的不等式,若遇到不满足的情况则return false
  4. 如果全都检验通过,则return true

代码如下

/**
 * @param {string[]} equations
 * @return {boolean}
 */
var equationsPossible = function(equations) {
    let parent = [];
    for(let i=0;i<26;i++){
        parent[i]=i;
    }
    for(let i=0;i<equations.length;i++){
        if(equations[i].charAt(1) == '='){
            let index1 = equations[i].charCodeAt(0) - 97;
            let index2 = equations[i].charCodeAt(3) - 97;
            union(parent,index1,index2);
        }
    }
    for(let i=0;i<equations.length;i++){
        if(equations[i].charAt(1) == '!'){
            let index1 = equations[i].charCodeAt(0) - 97;
            let index2 = equations[i].charCodeAt(3) - 97;
            if(find(parent,index1) == find(parent,index2)){
                return false;
            }
        }
    }
    return true;
};


function union(parent,index1,index2){
    let root1 = find(parent,index1);
    let root2 = find(parent,index2);
    parent[root1] = root2;
}

function find(parent,index){
    if(parent[index]!=index){
        parent[index] = find(parent,parent[index]);
    }
    return parent[index];
}