Skip to content

Commit 7c2bd4b

Browse files
authored
Create determine-if-two-strings-are-close.cpp
1 parent 7a98d65 commit 7c2bd4b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool closeStrings(string word1, string word2) {
7+
if (size(word1) != size(word2)) {
8+
return false;
9+
}
10+
vector<int> cnt1(26), cnt2(26);
11+
for (const auto& c : word1) {
12+
++cnt1[c - 'a'];
13+
}
14+
for (const auto& c : word2) {
15+
++cnt2[c - 'a'];
16+
}
17+
unordered_map<int, int> diff;
18+
for (int i = 0; i < size(cnt1); ++i) {
19+
if (!cnt1[i] && !cnt2[i]) {
20+
continue;
21+
}
22+
if (!cnt1[i] || !cnt2[i]) {
23+
return false;
24+
}
25+
++diff[cnt1[i]];
26+
--diff[cnt2[i]];
27+
}
28+
return all_of(cbegin(diff), cend(diff),
29+
[](const auto& kvp) {
30+
return kvp.second == 0;
31+
});
32+
}
33+
};

0 commit comments

Comments
 (0)