题目
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
(链接)https://leetcode-cn.com/problems/satisfiability-of-equality-equations/
并查集还是不太熟悉 这次才算是熟悉了。。。
时间:8ms 内存:11M
class Solution {
public:
int nums[26] ;
int find(int x) {
if (x == nums[x]) {
return x;
}
nums[x] = find(nums[x]);
return nums[x];
}
void unite(int a,int b) {
nums[find(a)] = find(b);
}
bool equationsPossible(vector<string>& equations) {
for (int i = 0; i < 26; i++){
nums[i]=i;
}
for (string s:equations) {
if (s[1] == '=') {
int x = s[0] - 'a';
int y = s[3] - 'a';
unite(x, y);
}
}
for (string s : equations) {
if (s[1] == '!') {
int x = s[0] - 'a';
int y = s[3] - 'a';
if (find(x) == find(y)) {
return false;
}
}
}
return true;
}
};