1 class Finder: 2 def __init__(self): 3 self.Parent = [i for i in range(26)] 4 def union(self, p, q): 5 self.Parent[self.find(p)] =self.find(q) 6 7 def find(self, p): 8 if self.Parent[p] != p: 9 return self.find(self.Parent[p]) 10 else: 11 return p 12 class Solution(object): 13 def equationsPossible(self, equations): 14 """ 15 :type equations: List[str] 16 :rtype: bool 17 """ 18 def convert(c): 19 return ord(c)-ord('a') 20 21 finder = Finder() 22 for e in equations: 23 if e.find("==") == 1: 24 left, right = convert(e[0]), convert(e[3]) 25 finder.union(left, right) 26 else: 27 pass 28 for e in equations: 29 if e.find("!=") == 1: 30 left, right = convert(e[0]), convert(e[3]) 31 if finder.find(left) == finder.find(right): 32 return False 33 return True
并查集方案