1+ #include < vector>
2+ #include < string>
3+ #include < unordered_map>
4+ using namespace std ;
5+
6+ class Solution {
7+ public:
8+ /* *
9+ * 执行用时 :16 ms, 在所有 C++ 提交中击败了25.68%的用户
10+ * 内存消耗 :11.2 MB, 在所有 C++ 提交中击败了50.00%的用户
11+ */
12+ unordered_map<char , char > eq;
13+
14+ bool equationsPossible (vector<string>& equations) {
15+ int n = equations.size ();
16+
17+ for (const string &s: equations) {
18+ bool flag1 = insert_node (eq, s[0 ]);
19+ bool flag2 = insert_node (eq, s[3 ]); // 插入
20+ if (s[1 ] == ' =' ) join (eq, s[0 ], s[3 ]);
21+ }
22+
23+ for (const string &s: equations) {
24+ if (s[1 ] == ' !' ) {
25+ char root1 = find (eq, s[0 ]);
26+ char root2 = find (eq, s[3 ]);
27+ if (root1 == root2) return false ;
28+ }
29+ }
30+
31+ return true ;
32+ }
33+
34+ bool is_exist (unordered_map<char , char >& set, char x) {
35+ return set.find (x) != set.end ();
36+ }
37+ bool insert_node (unordered_map<char , char >& set, char x) {
38+ if (is_exist (set, x)) return false ;
39+ set[x] = x;
40+ return true ;
41+ }
42+ char find (unordered_map<char , char >& set, char x) {
43+ if (set[x] == x) return x;
44+ return find (set, set[x]);
45+ }
46+ void join (unordered_map<char , char >& set, char x, char y) {
47+ char x_root = find (set, x);
48+ char y_root = find (set, y);
49+ set[y_root] = x_root;
50+ }
51+ };
0 commit comments