问题描述
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程
equations[i]
的长度为4
,并采用两种不同的形式之一:"a==b"
或"a!=b"
。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回
true
,否则返回false
。
示例
示例 1:
输入:["a==b","b!=a"] 输出:false 解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。示例 2:
输入:["b==a","a==b"] 输出:true 解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。示例 3:
输入:["a==b","b==c","a==c"] 输出:true示例 4:
输入:["a==b","b!=c","c==a"] 输出:false示例 5:
输入:["c==c","b==d","x!=z"] 输出:true提示:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0]
和equations[i][3]
是小写字母equations[i][1]
要么是'='
,要么是'!'
equations[i][2]
是'='
问题分析:
最近在学习图论,这是一道经典的可以使用并查集解决的问题。我们构建一个并查集,其中把所有相等的元素,union起来,这样当遇到!=符号时,去检查并查集中这俩元素是否之前已经连接了,如果已经连接就返回false,直到最后都没返回就返回true。
代码如下:
// 并查集模板
class UF{
private:
vector<int> parent;
public:
UF(int n){
for(int i = 0; i < n; ++i){
parent.push_back(i);
}
}
int find(int x){
if(x != parent[x]){
parent[x] = find(parent[x]);
}
return parent[x];
}
void _union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX != rootY){
parent[rootX] = rootY;
}
}
bool isConnected(int x, int y){
int rootX = find(x);
int rootY = find(y);
return rootX == rootY;
}
};
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
UF uf(26);
// 遍历==,构建并查集
for(auto& eq : equations){
if(eq[1] == '='){
uf._union(eq[0] - 'a', eq[3] - 'a');
}
}
// 遍历!=,检验并查集
for(auto& eq : equations){
if(eq[1] == '!'){
if(uf.isConnected(eq[0] - 'a', eq[3] - 'a')){
return false;
}
}
}
return true;
}
};