990. Satisfiability of Equality Equations

2020/11/01 leetcode 共 1412 字,约 5 分钟

title

problem link

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 1:

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.
Example 2:

Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Example 3:

Input: ["a==b","b==c","a==c"]
Output: true
Example 4:

Input: ["a==b","b!=c","c==a"]
Output: false
Example 5:

Input: ["c==c","b==d","x!=z"]
Output: true


Note:

1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] and equations[i][3] are lowercase letters
equations[i][1] is either '=' or '!'
equations[i][2] is '='

solution

class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        uf = {}

        def find(x):
            if uf[x] != x:
                uf[x] = find(uf[x])
            return uf[x]

        def union(a, b):
            uf.setdefault(a, a)
            uf.setdefault(b, b)
            uf[find(a)] = find(b)

        def is_connect(a, b):
            uf.setdefault(a, a)
            uf.setdefault(b, b)
            return find(a) == find(b)

        equals = [x for x in equations if x[1:3] == "=="]
        for ie in equals:
            a, b = ie[0], ie[3]
            union(a, b)
        not_equals = [x for x in equations if x[1:3] == "!="]
        for ie in not_equals:
            a, b = ie[0], ie[3]
            if is_connect(a, b):
                return False
        return True

Search

    Table of Contents