File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 2
2
// Space: O(1)
3
3
4
4
class Solution {
5
+ public:
6
+ bool equationsPossible (vector<string>& equations) {
7
+ UnionFind union_find (26 );
8
+ for (const auto & eqn : equations) {
9
+ int x = eqn[0 ] - ' a' ;
10
+ int y = eqn[3 ] - ' a' ;
11
+ if (eqn[1 ] == ' =' ) {
12
+ union_find.union_set (x, y);
13
+ }
14
+ }
15
+ for (const auto & eqn : equations) {
16
+ int x = eqn[0 ] - ' a' ;
17
+ int y = eqn[3 ] - ' a' ;
18
+ if (eqn[1 ] == ' !' ) {
19
+ if (union_find.find_set (x) == union_find.find_set (y)) {
20
+ return false ;
21
+ }
22
+ }
23
+ }
24
+ return true ;
25
+ }
26
+
27
+
28
+ private:
29
+ class UnionFind {
30
+ public:
31
+ UnionFind (const int n) : set_(n) {
32
+ iota (set_.begin (), set_.end (), 0 );
33
+ }
34
+
35
+ int find_set (const int x) {
36
+ if (set_[x] != x) {
37
+ set_[x] = find_set (set_[x]); // Path compression.
38
+ }
39
+ return set_[x];
40
+ }
41
+
42
+ bool union_set (const int x, const int y) {
43
+ int x_root = find_set (x), y_root = find_set (y);
44
+ if (x_root == y_root) {
45
+ return false ;
46
+ }
47
+ set_[min (x_root, y_root)] = max (x_root, y_root);
48
+ return true ;
49
+ }
50
+
51
+ private:
52
+ vector<int > set_;
53
+ };
54
+ };
55
+
56
+ // Time: O(n)
57
+ // Space: O(1)
58
+ class Solution2 {
5
59
public:
6
60
bool equationsPossible (vector<string>& equations) {
7
61
vector<vector<int >> graph (26 );
You can’t perform that action at this time.
0 commit comments