方法:并查集。
思路:相等的关系可以传递,最终的结果集必然是若干个集合,每个集合里的变量拥有相同的值,即处在同一个连通分量里。而不等关系则是两个变量在不同的连通分量里。
所以,先针对相等关系建立并查集,而后判断每个不等关系是否都满足即可。
代码:
class Solution {
// 并查集,这里并查集的根节点与下标相等。
public int[] parent=new int[26];
public int findParent(int t){
while(parent[t]!=t){
t=parent[t];
}
return t;
}
public void union(int a,int b){
int pa=findParent(a),pb=findParent(b);
if(pa==pb)return;
parent[pb]=pa;
}
public boolean equationsPossible(String[] equations) {
// 并查集初始化。
for(int i=0;i<parent.length;i++){
parent[i]=i;
}
for(int i=0;i<equations.length;i++){
if(equations[i].charAt(1)=='='){
union(equations[i].charAt(0)-'a',equations[i].charAt(3)-'a');
}
}
for(int i=0;i<equations.length;i++){
if(equations[i].charAt(1)=='!'){
if(findParent(equations[i].charAt(0)-'a')==findParent(equations[i].charAt(3)-'a')){
return false;
}
}
}
return true;
}
}