LeetCode/problems/cpp/determine-if-two-strings-are-close.cpp
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +02:00

43 lines
767 B
C++

#include <algorithm>
#include <array>
#include <string>
class Solution {
using freq_t = std::array<std::size_t, 26>;
freq_t freqs(const std::string& word)
{
freq_t f { 0 };
for (auto c : word) {
f[c - 'a']++;
}
return f;
}
int mask(const freq_t& f)
{
int m = 0;
for (auto c : f) {
m = (m << 1) | (c > 0);
}
return m;
}
public:
bool closeStrings(std::string word1, std::string word2)
{
auto f1 = freqs(word1);
auto m1 = mask(f1);
std::sort(f1.begin(), f1.end());
auto f2 = freqs(word2);
auto m2 = mask(f2);
std::sort(f2.begin(), f2.end());
return m1 == m2 && f1 == f2;
}
};