Article Directory
Title description
Ideas
- union-find: Since the return is
False
mainly a contradictory description of the previous equal sign transfer relationship, it is necessary to traverse the"=="
relationship first . Here the code reorganizes the original elements
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
- The official code is as follows
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