题目描述
思路
- union-find:由于返回
False
主要是在对之前等号传递关系的矛盾性描述,故需要先遍历"=="
关系,这里代码将 原元素重组了一下
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
data = collections.defaultdict()
def find_root(a):
return a if data[a]==a else find_root(data[a])
def union(a, b):
data[a] = b
# 将 "==" 放在 "!=" 的前面
data_equ = []
data_not = []
for one in equations:
if one[1] == "=":
data_equ.append(one)
else:
data_not.append(one)
equations = data_equ + data_not
for one in equations:
a, b = one[0], one[-1]
if one[1] == "=":
if a not in data:
data[a] = a
if b not in data:
data[b] = b
union(find_root(a), find_root(b)) # 合并
else: # !=
if a == b: return False # 对于 a!=a 返回Flase
if a in data and b in data:
if find_root(a) == find_root(b):
return False
else:
if a not in data:
data[a] = a
if b not in data:
data[b] = b
return True
- 官方代码如下
class Solution:
class UnionFind:
def __init__(self):
self.parent = list(range(26))
def find(self, index):
if index == self.parent[index]:
return index
self.parent[index] = self.find(self.parent[index])
return self.parent[index]
def union(self, index1, index2):
self.parent[self.find(index1)] = self.find(index2)
def equationsPossible(self, equations: List[str]) -> bool:
uf = Solution.UnionFind()
for st in equations:
if st[1] == "=":
index1 = ord(st[0]) - ord("a")
index2 = ord(st[3]) - ord("a")
uf.union(index1, index2)
for st in equations:
if st[1] == "!":
index1 = ord(st[0]) - ord("a")
index2 = ord(st[3]) - ord("a")
if uf.find(index1) == uf.find(index2):
return False
return True