Leetcode-990. 等式方程的可满足性 Satisfiability of Equality Equations (并查集) -超详细python

题目

给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:“a==b” 或 “a!=b”。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
链接:https://leetcode.com/problems/satisfiability-of-equality-equations/

Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: “a==b” or “a!=b”. Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

Example:

Input: [“a==b”,“b!=a”]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.

思路及代码

并查集 Union-Find
class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        def find(x):
            if x != root[x]:
                root[x] = find(root[x])
            return root[x]
        
        root = {}
        for eq in equations:
      		# 初始化
            if eq[0] not in root:
                root[eq[0]] = eq[0]
            if eq[3] not in root:
                root[eq[3]] = eq[3]
                
            if eq[1] == "=":
                root[find(eq[0])] = find(eq[3])
                
        for eq in equations:
            if eq[1] == "!" and root[find(eq[0])] == find(eq[3]):
                    return False
        return True

复杂度

T = O ( n ) T = O(n) T=O(n)
S = O ( n ) S = O(n) S=O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值