2506.统计相似字符串对的数目
链接:2506.统计相似字符串对的数目
难度:Easy
标签:位运算、数组、哈希表、字符串
简介:如果两个字符串由相同的字符组成,则认为这两个字符串 相似 。请你找出满足字符串 words[i] 和 words[j] 相似的下标对 (i, j) ,并返回下标对的数目,其中 0 <= i < j <= word.length - 1 。
题解 1 - cpp
- 编辑时间:2022-12-18
- 执行用时:12ms
- 内存消耗:12.4MB
- 编程语言:cpp
- 解法介绍:哈希统计前面的数量。
class Solution {
public:
int similarPairs(vector<string>& words) {
unordered_map<int, int> m;
int ans = 0;
for (auto &word : words) {
int num = toNum(word);
ans += m[num];
m[num]++;
}
return ans;
}
int toNum(string &word) {
int ans = 0;
for (auto &ch : word) {
ans |= (1 << (ch - 'a'));
}
return ans;
}
};