题目地址:
https://leetcode.com/problems/satisfiability-of-equality-equations/
给定一系列等式和不等式总共
n
n
n个,以字符串形式给出,每个字符串
s
s
s长为
3
3
3,其中
s
[
0
]
s[0]
s[0]和
s
[
3
]
s[3]
s[3]是英文小写字母,
s
[
1
:
2
]
s[1:2]
s[1:2]或者是"=="
或者是"!="
。问这些等式是否有矛盾。
可以用并查集,先将相等的变量合并起来,然后再逐一检查不等式,看看有没有矛盾。代码如下:
public class Solution {
class UnionFind {
private int[] p;
public UnionFind(int size) {
p = new int[size];
for (int i = 0; i < size; i++) {
p[i] = i;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public void union(int x, int y) {
int px = find(x), py = find(y);
if (px != py) {
p[px] = py;
}
}
}
public boolean equationsPossible(String[] equations) {
UnionFind uf = new UnionFind(26);
for (String eq : equations) {
if (eq.charAt(1) == '=') {
uf.union(eq.charAt(0) - 'a', eq.charAt(3) - 'a');
}
}
for (String eq : equations) {
// 如果发现不等式与某个等式的传递关系有矛盾,则返回false
if (eq.charAt(1) == '!' && uf.find(eq.charAt(0) - 'a') == uf.find(eq.charAt(3) - 'a')) {
return false;
}
}
return true;
}
}
时空复杂度 O ( n ) O(n) O(n)。