LC990. 等式方程的可满足性

注意并查集的应用,这题的思路是把等于的两个字母连通,又因为并查集的传递性,和等于的传递性相同。最终就是相等的和由于传递性相等的被放在同一个集合。这样分成了多个连通区域。
之后,不等的必须在不同的区域才算正确,因为同一个区域的必须保证相等。
所以遍历一遍判断不等的里有没有在同一区域的,如果有返回False。没有返回True

def equationsPossible(self, equations):
        """
        :type equations: List[str]
        :rtype: bool
        """
        n = len(equations)
        parent = list(range(26))                   #注意因为是用数组存储,所以需要把字母给转换成数字并且对应数组的下标。一共26个字母
        def find(x):
            if x != parent[x]:
                parent[x] = find(parent[x])
            return parent[x]
        def union(index1,index2):
            parent[find(index1)] = find(index2)
        for st in equations:
            if st[1] == "=":
                union(ord(st[0])-ord("a"),ord(st[3])-ord("a"))                #这里减去的目的是匹配数组的下标
        for st in equations:
            if st[1] == "!":
                if find(ord(st[0])-ord("a")) == find(ord(st[3])-ord("a")):
                    return False
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值