-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1657.determine-if-two-strings-are-close.cpp
75 lines (68 loc) · 1.53 KB
/
1657.determine-if-two-strings-are-close.cpp
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
/*
* @lc app=leetcode id=1657 lang=cpp
*
* [1657] Determine if Two Strings Are Close
*/
// @lc code=start
class Solution
{
public:
bool closeStrings(string word1, string word2)
{
map<char, int> a, b;
for (auto k : word1)
{
a[k]++;
}
for (auto k : word2)
{
b[k]++;
}
map<int, set<char>> x, y;
vector<int> v1, v2;
for (char i = 'a'; i <= 'z'; i++)
{
if (a[i] != 0)
{
x[a[i]].insert(i);
}
if (b[i] != 0)
{
y[b[i]].insert(i);
}
}
for (char i = 'a'; i <= 'z'; i++)
{
if (a[i] == 0 && b[i] == 0)
continue;
if (a[i] == 0 || b[i] == 0)
{
return false;
}
if (b[i])
{
if (a[i] == b[i])
{
x[a[i]].erase(i);
a[i] = 0;
b[i] = 0;
continue;
}
else
{
if (x[b[i]].empty())
{
return false;
}
char c = *x[b[i]].begin();
x[b[i]].erase(c);
x[a[i]].erase(i);
a[c] = a[i];
x[a[i]].insert(c);
}
}
}
return true;
}
};
// @lc code=end