【Leetcode】990. Satisfiability of Equality Equations

题目地址:

https://leetcode.com/problems/satisfiability-of-equality-equations/

给定一系列等式和不等式总共 n n n个,以字符串形式给出,每个字符串 s s s长为 3 3 3,其中 s [ 0 ] s[0] s[0] s [ 3 ] s[3] s[3]是英文小写字母, s [ 1 : 2 ] s[1:2] s[1:2]或者是"=="或者是"!="。问这些等式是否有矛盾。

可以用并查集,先将相等的变量合并起来,然后再逐一检查不等式,看看有没有矛盾。代码如下:

public class Solution {
    
    class UnionFind {
        private int[] p;
        public UnionFind(int size) {
            p = new int[size];
            for (int i = 0; i < size; i++) {
                p[i] = i;
            }
        }
        
        public int find(int x) {
            if (p[x] != x) {
                p[x] = find(p[x]);
            }
            return p[x];
        }
        
        public void union(int x, int y) {
            int px = find(x), py = find(y);
            if (px != py) {
                p[px] = py;
            }
        }
    }
    
    public boolean equationsPossible(String[] equations) {
        UnionFind uf = new UnionFind(26);
        for (String eq : equations) {
            if (eq.charAt(1) == '=') {
                uf.union(eq.charAt(0) - 'a', eq.charAt(3) - 'a');
            }
        }
    
        for (String eq : equations) {
        	// 如果发现不等式与某个等式的传递关系有矛盾,则返回false
            if (eq.charAt(1) == '!' && uf.find(eq.charAt(0) - 'a') == uf.find(eq.charAt(3) - 'a')) {
                return false;
            }
        }
        
        return true;
    }
}

时空复杂度 O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值