LeetCode 990. 等式方程的可满足性

题目链接

990. 等式方程的可满足性

题目分析

这个题目其实非常典型的并查集的内容了,我们首先先对等号的式子建立一个并查集。然后再使用一轮循环去判断不等号的情况,如果不等号的左右两个符号属于同一个集合,那么就说明这个式子有问题,返回false即可。否则就返回true。

代码实现

class Solution {
    int[] anc = new int[26];
    public boolean equationsPossible(String[] equations) {
        for(int i = 0; i < anc.length; i++){
            anc[i] = i;
        }
        for(String str: equations){
            char a = str.charAt(0);
            char b = str.charAt(3);
            char ops = str.charAt(1);
            if(ops == '='){
                int anc1 = find(a - 'a');
                int anc2 = find(b - 'a');
                anc[anc1] = anc2;
            }
        }
        for(String str: equations){
            char a = str.charAt(0);
            char b = str.charAt(3);
            char ops = str.charAt(1);
            if(ops == '!'){
                int anc1 = find(a - 'a');
                int anc2 = find(b - 'a');
                if(anc1 == anc2){
                    return false;
                }
            }
        }
        return true;
    }

    public int find(int x){
        while(x != anc[x]){
            x = anc[x];
        }
        return x;
    }
}
posted @ 2020-09-17 11:20  ZJPang  阅读(120)  评论(0编辑  收藏  举报