Satisfiability of Equality Equations
update Feb 11 2019, 22:25
Given an array equations of strings that represent relationships between variables, each string equations[i]
has length 4 and takes one of two different forms: "a==b"
or "a!=b"
. Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.
Example 1:
Input: ["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: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Example 3:
Input: ["a==b","b==c","a==c"]
Output: true
Example 4:
Input: ["a==b","b!=c","c==a"]
Output: false
Example 5:
Input: ["c==c","b==d","x!=z"]
Output: true
Note:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] and equations[i][3] are lowercase letters
equations[i][1] is either '=' or '!'
equations[i][2] is '='
Basic Idea:
基本思路就是把每个相等的部分放到一起,然后判断是否所有的 a!=b
的equation成立,如果成立,需满足a和b不在同一个部分。
这就是典型的并查集的思路,我们先对所有的 a==b
做union,然后查看不等关系中左右值是否在同一个block里,如果在,则说明不成立。
Java Code:
class Solution {
private int[] idxs;
private int find(int x) {
if (idxs[x] == x) return x;
else {
idxs[x] = find(idxs[x]);
}
return idxs[x];
}
private void union(int x, int y) {
int root_x = find(x), root_y = find(y);
if (root_x == root_y) return;
idxs[root_x] = root_y;
}
public boolean equationsPossible(String[] equations) {
// initialize
idxs = new int[256];
for (int i = 0; i < idxs.length; ++i) idxs[i] = i;
// process "==" first
for (String equation : equations) {
if (equation.charAt(1) == '=') {
union(equation.charAt(0), equation.charAt(3));
}
}
// check all "!="
for (String equation : equations) {
if (equation.charAt(1) == '!') {
if (find(equation.charAt(0)) == find(equation.charAt(3))) {
return false;
}
}
}
return true;
}
}