Untitled
unknown
plain_text
12 days ago
1.0 kB
4
Indexable
#include <iostream> #include <vector> #include <unordered_map> using namespace std; int countComplementaryPairs(vector<string>& words) { unordered_map<int, int> bitmask_count; int count_pairs = 0; for (const string& word : words) { int mask = 0; // Compute the bitmask for the current word for (char ch : word) { mask ^= (1 << (ch - 'a')); // Toggle the corresponding bit } // Case 1: Count exact matches (same bitmask) count_pairs += bitmask_count[mask]; // Case 2: Count bitmasks differing by exactly one bit for (int i = 0; i < 26; ++i) { count_pairs += bitmask_count[mask ^ (1 << i)]; } // Store the current bitmask in the hashmap bitmask_count[mask]++; } return count_pairs; } // Driver function int main() { vector<string> words = {"abac", "cab", "abc", "cba", "aa", "bb"}; cout << "Number of complementary pairs: " << countComplementaryPairs(words) << endl; return 0; }
Editor is loading...
Leave a Comment