You are given an array of strings equations
that represent relationships between variables where each string equations[i]
is of length 4
and takes one of two different forms: "xi==yi"
or "xi!=yi"
.Here, xi
and yi
are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true
if it is possible to assign integers to variable names so as to satisfy all the given equations, or false
otherwise.
Example 1:
Input: equations = ["a==b","b!=a"] Output: false Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.
Example 2:
Input: equations = ["b==a","a==b"] Output: true Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Constraints:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0]
is a lowercase letter.equations[i][1]
is either'='
or'!'
.equations[i][2]
is'='
.equations[i][3]
is a lowercase letter.
题目链接:https://leetcode.com/problems/satisfiability-of-equality-equations/
题目大意:给若然形如x==y或x!=y的式子,问是否存在冲突
题目分析:并查集,相等的先合并,不等的看是否在同一集合即可
2ms,时间击败66.83%
class Solution {
class UFSet {
int n;
int[] fa;
UFSet(int n) {
this.n = n;
this.fa = new int[n + 1];
for (int i = 0; i <= n; i++) {
fa[i] = i;
}
}
int find(int x) {
if (x == fa[x]) {
return x;
}
fa[x] = find(fa[x]);
return fa[x];
}
void union(int a, int b) {
int r1 = find(a);
int r2 = find(b);
if (r1 != r2) {
fa[r1] = r2;
}
}
}
public boolean equationsPossible(String[] equations) {
UFSet ufs = new UFSet(26);
for (String s : equations) {
int x = s.charAt(0) - 'a';
int y = s.charAt(3) - 'a';
if (s.charAt(1) == '=') {
ufs.union(x, y);
}
}
for (String s : equations) {
if (s.charAt(1) == '!') {
int x = s.charAt(0) - 'a';
int y = s.charAt(3) - 'a';
if (ufs.find(x) == ufs.find(y)) {
return false;
}
}
}
return true;
}
}