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'='
等式方程的可满足性。
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是并查集union find。如果中间是等号,说明等号两边的内容应该是同组的,反之则是不同组的。先扫描是等号的,将同组的东西都组合起来;然后扫描不等号的两边,看看是否有跟已经union好的内容有矛盾的地方。
时间 ?
空间 ?
Java实现
1 class Solution { 2 public boolean equationsPossible(String[] equations) { 3 int len = equations.length; 4 int[] parent = new int[26]; 5 for (int i = 0; i < 26; i++) { 6 parent[i] = i; 7 } 8 for (String str : equations) { 9 if (str.charAt(1) == '=') { 10 int index1 = str.charAt(0) - 'a'; 11 int index2 = str.charAt(3) - 'a'; 12 union(parent, index1, index2); 13 } 14 } 15 for (String str : equations) { 16 if (str.charAt(1) == '!') { 17 int index1 = str.charAt(0) - 'a'; 18 int index2 = str.charAt(3) - 'a'; 19 if (find(parent, index1) == find(parent, index2)) { 20 return false; 21 } 22 } 23 } 24 return true; 25 } 26 27 private void union(int[] parent, int index1, int index2) { 28 parent[find(parent, index1)] = find(parent, index2); 29 } 30 31 private int find(int[] parent, int index) { 32 while (parent[index] != index) { 33 parent[index] = parent[parent[index]]; 34 index = parent[index]; 35 } 36 return index; 37 } 38 }