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]
andequations[i][3]
are lowercase lettersequations[i][1]
is either'='
or'!'
equations[i][2]
is'='
题目理解:
给定一系列的相等和不等关系,问所有的式子能否同时成立
解题思路:
使用并查集,不知道的话可以自己百度一下。
遇到等式时,将所有相等的元素union起来,遇到不等式时先不处理,但是记录下来。
遍历所有的式子之后,遍历不等式,如果不等式两端的变量的root是相同的,说明这两个元素在等式当中,又在不等式当中,因此所有的式子不能同时成立。这是一种效率较高的解法。
class Solution {
int[] root = new int[26];
public void union(int a, int b){
root[find(a)] = root[find(b)];
}
public int find(int num){
if(root[num] != num)
root[num] = find(root[num]);
return root[num];
}
public boolean equationsPossible(String[] equations) {
for(int i = 0; i < 26; i++)
root[i] = i;
List<String> list = new ArrayList<>();
for(String str : equations){
char[] chs = str.toCharArray();
if(chs[1] == '=')
union(chs[0] - 'a', chs[3] - 'a');
else
list.add(str);
}
for(String str : list){
char[] chs = str.toCharArray();
if(find(chs[0] - 'a') == find(chs[3] - 'a'))
return false;
}
return true;
}
}