-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircle of strings
62 lines (54 loc) Β· 1.45 KB
/
Circle of strings
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
#include <vector>
#include <string>
#include <unordered_map>
class Solution {
private:
std::vector<int> parent;
std::vector<int> rank;
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
void unite(int x, int y) {
int px = find(x), py = find(y);
if (px == py) return;
if (rank[px] < rank[py])
parent[px] = py;
else if (rank[px] > rank[py])
parent[py] = px;
else {
parent[py] = px;
rank[px]++;
}
}
public:
int isCircle(std::vector<std::string> &arr) {
int n = arr.size();
parent.resize(26);
rank.resize(26, 0);
for (int i = 0; i < 26; i++)
parent[i] = i;
std::vector<int> inDegree(26, 0), outDegree(26, 0);
std::unordered_map<int, bool> seen;
for (const auto &s : arr) {
int u = s.front() - 'a';
int v = s.back() - 'a';
unite(u, v);
outDegree[u]++;
inDegree[v]++;
seen[u] = seen[v] = true;
}
int root = -1;
for (const auto &pair : seen) {
int vertex = pair.first;
if (root == -1)
root = find(vertex);
else if (find(vertex) != root)
return 0;
if (inDegree[vertex] != outDegree[vertex])
return 0;
}
return 1;
}
};