Leetcode 893. Groups of Special
You are given an array A
of strings. Two strings S
and T
are considered special-equivalent if after any number of moves, S
can become T
.
A move consists of choosing two indices i
and j
with the same parity (both even or both odd) and swapping S[i]
with S[j]
.
Return the number of groups of special-equivalent strings from A
.
A
be?For the sake of this problem, we assume:
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
int numSpecialEquivGroups(std::vector<std::string>& A) {
std::unordered_set<std::string> unique_groups;
for (const auto &s : A) {
std::string even, odd;
// Separate characters by even and odd indices
for (int i = 0; i < s.size(); ++i) {
if (i % 2 == 0)
even += s[i];
else
odd += s[i];
}
// Sort both parts
std::sort(even.begin(), even.end());
std::sort(odd.begin(), odd.end());
// Concatenate sorted parts and add to the set
unique_groups.insert(even + odd);
}
return unique_groups.size();
}
int main() {
std::vector<std::string> A = {"abc","acb","bac","bca","cab","cba"};
std::cout << "Number of groups: " << numSpecialEquivGroups(A) << std::endl;
return 0;
}
This approach ensures we effectively group all special-equivalent strings and then determine the count of such groups.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?