Leetcode 2506: Count Pairs Of Similar Strings
Categories: Algorithm
problem:
source: Count Pairs Of Similar Strings
Identify problem
given the vector of strings, we have to identify the number of strings that has matching occurance of char(alphabet).
Approach
use bitwise operation
Code:
int similarPairs(vector<string>& words) {
unordered_map<int, int> m;
for (auto &w : words)
{
m[accumulate(begin(w), end(w), 0,
[](int res, char ch)
{
return res | (1 << (ch - 'a'));
})] += 1;
}
return accumulate(begin(m), end(m), 0,
[](int res, const auto &p)
{
return res + p.second * (p.second - 1) / 2;
});
}
note
std::accumulate
could be found in #include <numeric>
. Also note that the type returned by std::accumulate
follows the initial value(3rd param of accumulate function).
https://math.stackexchange.com/questions/2214839/exactly-how-does-the-equation-nn-1-2-determine-the-number-of-pairs-of-a-given
Leave a comment