当前位置:网站首页>Leetcode - 990: equations of satisfiability
Leetcode - 990: equations of satisfiability
2022-07-30 09:08:00 【chrysanthemum bat】
题目
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 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
解题
The concept of check union 来源
方法一:并查集
参考链接
due to equal elements,放到一个集合,So there needs to be multiple collections.
If the equals sign is involved in associating two sets,Then it will also involve the merge operation of the collection.
for unequal elements,The set can be determined,if within a set,就返回false
下图是 Full compression of the tree structure,也就是在findinside the function.
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]);//The parent node of all association nodes points to the root node of the association
return parent[index];
}
void unite(int index1,int index2){
//关联(Point the parent of the root node of the first variable to the root node of the second variable)
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;
}
};
边栏推荐
- The blockbuster IP that has been popular in the world for 25 years, the new work has become a script paradise
- 出网判断:
- Risk Register
- 41.【vector应用操作2】
- 最右的一道面试算法题,--特殊基因
- 基于JSP实现校园二手交易平台
- Leetcode 2.两数相加 两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的。
- Why does typescript2-typescript add type support to js
- npm指令
- 39.【vector动态数组定义及初始化】
猜你喜欢
随机推荐
Detailed explanation of 4D words: C language three-point chess advanced + N-piece chess recursive dynamic judgment of winning or losing
信号完整性测试
数据库连接池的使用
SQL注入漏洞(postgresql注入)
typescript8 - type annotations
剖析SGI STL空间配置器(一 、辅助接口函数)
网络/信息安全顶刊及相关期刊会议
ipset restore命令维护set,但原已存在的条目未删除掉
一文读懂二十种开关电源拓扑结构
SEER数据库中“手术变量(RX SUMM-SURG OTH REG/DIS )”下的字段解释
input标签的tabindex属性 & a标签的tabindex属性
IDEA设置System.out.println()和main方法快捷键
英语语法-名词性从句
手把手教学OneOS FOTA升级
Dynamic Lead Time Promising
剖析SGI STL空间配置器(allocate内存分配函数)
【微信小程序】页面事件
Leetcode 2.两数相加 两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的。
【Kotlin 中的类和继承】
DDR、GDDR、QDR的区别