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