【Leetcode】并查集
990. 等式方程的可满足性
1 class Solution { 2 public boolean equationsPossible(String[] equations) { 3 int[] parent = new int[26];//存放节点的父节点 4 for(int i = 0; i < 26; i++){ 5 parent[i] = i;//初始化自己是自己的父节点 6 } 7 for(String equation: equations){ 8 int index1 = equation.charAt(0)-'a'; 9 int index2 = equation.charAt(3)-'a'; 10 if(equation.charAt(1) == '='){//相等则合并在一个连通集合中 11 union(parent, index1, index2); 12 } 13 } 14 for(String equation: equations){ 15 if(equation.charAt(1) == '!'){//不等但是在一个连通集合中 说明矛盾 16 int parent1 = find(parent, equation.charAt(0)-'a'); 17 int parent2 = find(parent,equation.charAt(3)-'a'); 18 if(parent1 == parent2){//顶层节点相同 19 return false; 20 } 21 } 22 } 23 return true; 24 } 25 private void union(int[] parent, int index1, int index2){ 26 parent[find(parent,index1)] = find(parent,index2);//index2的父等于index1的父 27 } 28 private int find(int[] parent, int index){//查找顶层节点 29 while(parent[index] != index){ 30 index = parent[index];//一直向上找,直到找到顶层父 31 } 32 //如果节点的父节点是自己则是顶层节点 直接返回 33 return index; 34 } 35 }