Leetcode 990.等式方程的可滿足性(Satisfiability of Equality Equations)

Leetcode 990.等式方程的可滿足性

1 題目描述(Leetcode題目鏈接

  給定一個由表示變量之間關係的字符串方程組成的數組,每個字符串方程 equations[i] 的長度爲 4,並採用兩種不同的形式之一:“a==b” 或 “a!=b”。在這裏,a 和 b 是小寫字母(不一定不同),表示單字母變量名。

只有當可以將整數分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。

輸入:["a==b","b!=a"]
輸出:false
解釋:如果我們指定,a = 1 且 b = 1,那麼可以滿足第一個方程,但無法滿足第二個方程。沒有辦法分配變量同時滿足這兩個方程。
輸出:["b==a","a==b"]
輸入:true
解釋:我們可以指定 a = 1 且 b = 1 以滿足滿足這兩個方程。
輸入:["a==b","b==c","a==c"]
輸出:true

提示:

  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] 和 equations[i][3] 是小寫字母
  • equations[i][1] 要麼是 ‘=’,要麼是 ‘!’
  • equations[i][2] 是 ‘=’

2 題解

  並查集。

class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        candidates = set()      # 記錄候選
        parent = collections.defaultdict(str) # 節點的從屬關係
        for i in string.ascii_lowercase:
            parent[i] = i

        def find(p):
            while p != parent[p]: p = parent[p]
            return p

        def union(p, q):
            proot = find(p)
            qroot = find(q)
            if proot == qroot:
                return
            parent[proot] = qroot
        
        # 通過==構建集合,並將!=的加入候選
        for equation in equations:
            p, q = equation[0], equation[3]
            if equation[1] == "=":
                union(p, q)
            else:
                candidates.add(equation)

        for equation in candidates:
            p, q = equation[0], equation[3]
            if find(p) == find(q):
                return False           

        return True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章