Description
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.
Examples
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 = [“ba","ab”]
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.
思路
感觉就是用并查集,判断两个单词是否在同一个簇中,要注意的是,需要先进行 “==” 的union,再进行 “!=” 的判断,因为没有操作来存储 “!=” 的约束
代码
class Solution {
public void union(int[] parents, int x, int y) {
int px = findParent(parents, x);
int py = findParent(parents, y);
if (px != py)
parents[px] = py;
}
public int findParent(int[] parents, int x) {
if(parents[x] != x)
parents[x] = findParent(parents, parents[x]);
return parents[x];
}
public boolean equationsPossible(String[] equations) {
int[] parents = new int[26];
for (int i = 0; i < parents.length; i++)
parents[i] = i;
for (String eq: equations) {
if (eq.charAt(1) == '=')
union(parents, eq.charAt(0) - 'a', eq.charAt(3) - 'a');
}
for (String eq: equations) {
if (eq.charAt(1) == '!') {
int x = findParent(parents, eq.charAt(0) - 'a');
int y = findParent(parents, eq.charAt(3) - 'a');
if (x == y)
return false;
}
}
return true;
}
}