-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSatisfiabilityOfEqualityEquations.java
87 lines (85 loc) · 2.62 KB
/
SatisfiabilityOfEqualityEquations.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*https://leetcode.com/problems/satisfiability-of-equality-equations/*/
class Solution {
int[] parent, rank;
public boolean equationsPossible(String[] equations) {
parent = IntStream.rangeClosed(0,25).toArray();
rank = new int[26];
// Arrays.sort(equations,(a,b)->(a.charAt(1) == '=' ? -1 : b.charAt(1) == '=' ? 1 : 0));
Arrays.sort(equations,(a,b)->(b.charAt(1)-a.charAt(1)));
for (String equation : equations)
{
boolean isPossible = union(equation.charAt(0)-'a',equation.charAt(3)-'a',equation.charAt(1) == '!' ? false : true);
if (!isPossible) return false;
}
return true;
}
private boolean union(int x, int y, boolean status)
{
int parentX = find(x);
int parentY = find(y);
if (parentX == parentY && !status) return false;
if (status)
{
if (rank[parentX] > rank[parentY])
{
parent[parentY] = parentX;
}
else
{
parent[parentX] = parentY;
if (rank[parentX] == rank[parentY])
++rank[parentY];
}
}
return true;
}
private int find(int x)
{
if (parent[x] == x) return x;
parent[x] = find(parent[x]);
return parent[x];
}
}
class Solution {
int[] parent, rank;
public boolean equationsPossible(String[] equations) {
parent = IntStream.rangeClosed(0,25).toArray();
rank = new int[26];
for (String equation : equations)
{
if (equation.charAt(1) == '=')
{
int x = equation.charAt(0)-'a';
int y = equation.charAt(3)-'a';
int parentX = find(x);
int parentY = find(y);
if (rank[parentX] > rank[parentY])
parent[parentY] = parentX;
else
{
parent[parentX] = parentY;
if (rank[parentX] == rank[parentY])
++rank[parentY];
}
}
}
for (String equation : equations)
{
if (equation.charAt(1) == '!')
{
int x = equation.charAt(0)-'a';
int y = equation.charAt(3)-'a';
int parentX = find(x);
int parentY = find(y);
if (parentX == parentY) return false;
}
}
return true;
}
private int find(int x)
{
if (parent[x] == x) return x;
parent[x] = find(parent[x]);
return parent[x];
}
}