[LeetCode] Count Pairs Of Similar Strings

2506. Count Pairs Of Similar Strings

You are given a 0-indexed string array words.

Two strings are similar if they consist of the same characters.

  • For example, “abca” and “cba” are similar since both consist of characters ‘a’, ‘b’, and ‘c’.
  • However, “abacba” and “bcfd” are not similar since they do not consist of the same characters.

Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int similarPairs(vector<string>& words) {
unordered_map<int,int> bits;
int res = 0;
for(auto w : words) {
int now = 0;
for(auto& ch : w) {
now |= (1<<(ch-'a'));
}
res += bits[now];
bits[now] += 1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/18/PS/LeetCode/count-pairs-of-similar-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.