注意并查集的应用,这题的思路是把等于的两个字母连通,又因为并查集的传递性,和等于的传递性相同。最终就是相等的和由于传递性相等的被放在同一个集合。这样分成了多个连通区域。
之后,不等的必须在不同的区域才算正确,因为同一个区域的必须保证相等。
所以遍历一遍判断不等的里有没有在同一区域的,如果有返回False。没有返回True
def equationsPossible(self, equations):
"""
:type equations: List[str]
:rtype: bool
"""
n = len(equations)
parent = list(range(26)) #注意因为是用数组存储,所以需要把字母给转换成数字并且对应数组的下标。一共26个字母
def find(x):
if x != parent[x]:
parent[x] = find(parent[x])
return parent[x]
def union(index1,index2):
parent[find(index1)] = find(index2)
for st in equations:
if st[1] == "=":
union(ord(st[0])-ord("a"),ord(st[3])-ord("a")) #这里减去的目的是匹配数组的下标
for st in equations:
if st[1] == "!":
if find(ord(st[0])-ord("a")) == find(ord(st[3])-ord("a")):
return False
return True