当前位置:网站首页>leetcode-990:等式方程的可满足性
leetcode-990:等式方程的可满足性
2022-07-30 07:41:00 【菊头蝙蝠】
题目
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 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
解题
查并集的概念 来源
方法一:并查集
参考链接
由于相等的元素,放到一个集合,因此需要有多个集合。
如果等号涉及到关联两个集合,那么还会涉及到集合的合并操作。
对于不相等的元素,可以判断所在集合,如果在一个集合内,就返回false
下图是 对树结构的完全压缩,也就是在find函数里面进行的。
class UnionFind{
private:
vector<int> parent;
public:
UnionFind(){
parent.resize(26);
iota(parent.begin(),parent.end(),0);
}
int find(int index){
//查找根节点
if(index==parent[index]) return index;
parent[index]=find(parent[index]);//所有关联节点的父节点都指向关联的根节点
return parent[index];
}
void unite(int index1,int index2){
//关联(将第一个变量的根节点的父节点指向第二个变量的根节点)
parent[find(index1)]=find(index2);
}
};
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
UnionFind uf;
for(string& s:equations){
if(s[1]=='='){
uf.unite(s[0]-'a',s[3]-'a');
}
}
for(string& s:equations){
if(s[1]=='!'){
if(uf.find(s[0]-'a')==uf.find(s[3]-'a')) return false;
}
}
return true;
}
};
边栏推荐
- 【蓝桥杯选拔赛真题45】Scratch猫鼠游戏 少儿编程scratch蓝桥杯选拔赛真题讲解
- 代币(双代币)系统研究
- 潜心打磨,主动求变——这群技术排头兵,如何做好底层开发这件事?
- Portable small fan PD power chip
- What convenience does the RFID fixed asset inventory system bring to enterprises?
- golang grpc protoc 环境配置
- Delphi仿制Web的导航
- typescript1-typescript是什么
- 你好,我的新名字叫 “铜锁 / Tongsuo”
- MagicDraw secondary development process
猜你喜欢
随机推荐
typescript6-简化运行ts的步骤
【微信小程序】页面事件
typescript2-typescript为什么给js添加类型支持
【网络攻防】常见的网络攻防技术——黑客攻防(通俗易懂版)
香港服务器iis配置web服务器如何操作?
Lenovo Notebook How to Change Windows 10 Boot Logo Icon
风险登记册
typescript5 - compile and install ts code
RFID固定资产盘点系统给企业带来哪些便利?
typescript1-typescript是什么
typescript1 - what is typescript
2022年施工企业数字化转型思考,施工企业数字化转型之路
孙洪鹤讲教材:原点+众筹+产品,逆向营销实战操作方案
Common configuration
电脑文档误删除怎么恢复,恢复误删除电脑文档的方法
input标签的tabindex属性 & a标签的tabindex属性
【小程序专栏】总结uniapp开发小程序的开发规范
防止资源导出失败
opencv可以有多有趣
Limit injection record of mysql injection in No. 5 dark area shooting range