当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
随机推荐
linux安装mysql8参考指引
英语语法-名词性从句
Thinking about digital transformation of construction enterprises in 2022, the road to digital transformation of construction enterprises
ES: 箭头函数和包裹它的代码共享相同的this
MySql Detailed Basics
LeetCode:647. 回文子串
OA项目之待开会议&历史会议&所有会议
OA Project Pending Meeting & History Meeting & All Meetings
经典毕业设计:基于SSM实现高校后勤报修系统
用代码收集每天热点内容信息,并发送到自己的邮箱
MongoDB - 千万级数据脚本过滤笔记
MagicDraw secondary development process
[Unity]UI切换环形滚动效果
test3
Hands-on teaching OneOS FOTA upgrade
求大佬解答,这种 sql 应该怎么写?
【无标题】
数据分发服务 (DDS) 内置主题
typescript3-ts对比js的差别
typescript1-typescript是什么