Input: words =["aba","aabb","abcd","bac","aabc"]Output: 2Explanation: There are 2 pairs that satisfy the conditions:- i =0 and j =1: both words[0] and words[1] only consist of characters 'a' and 'b'.- i =3 and j =4: both words[3] and words[4] only consist of characters 'a','b', and 'c'.
Input: words =["aabb","ab","ba"]Output: 3Explanation: There are 3 pairs that satisfy the conditions:- i =0 and j =1: both words[0] and words[1] only consist of characters 'a' and 'b'.- i =0 and j =2: both words[0] and words[2] only consist of characters 'a' and 'b'.- i =1 and j =2: both words[1] and words[2] only consist of characters 'a' and 'b'.
Two strings are similar if they have the same set of characters. We can represent the set of characters in a string as a bitmask of 26 bits (one for each lowercase letter). Strings with the same bitmask are similar.
classSolution {
publicintsimilarPairs(String[] words) {
Map<Integer, Integer> mp =new HashMap<>();
for (String w : words) {
int mask = 0;
for (char ch : w.toCharArray()) mask |= 1 << (ch -'a');
mp.put(mask, mp.getOrDefault(mask, 0) + 1);
}
int ans = 0;
for (int c : mp.values()) ans += c * (c - 1) / 2;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funsimilarPairs(words: Array<String>): Int {
val mp = mutableMapOf<Int, Int>()
for (w in words) {
var mask = 0for (ch in w) mask = mask or (1 shl (ch - 'a'))
mp[mask] = mp.getOrDefault(mask, 0) + 1 }
var ans = 0for (c in mp.values) ans += c * (c - 1) / 2return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsimilarPairs(self, words: list[str]) -> int:
from collections import Counter
mp = Counter()
for w in words:
mask =0for ch in w:
mask |=1<< (ord(ch) - ord('a'))
mp[mask] +=1 ans =0for c in mp.values():
ans += c * (c -1) //2return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnsimilar_pairs(words: Vec<String>) -> i32 {
use std::collections::HashMap;
letmut mp = HashMap::new();
for w in&words {
letmut mask =0;
for ch in w.chars() {
mask |=1<< (ch asu8-b'a');
}
*mp.entry(mask).or_insert(0) +=1;
}
letmut ans =0;
for&c in mp.values() {
ans += c * (c -1) /2;
}
ans
}
}