-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path893groups_of_special_equivalent_strings.py
55 lines (38 loc) · 1.87 KB
/
893groups_of_special_equivalent_strings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:
Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
one line solution
from collections import Counter
class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len({tuple(tuple(sorted(Counter(S[j::2]).items())) for j in range(2)) for S in A})
"""
from collections import Counter
class Solution:
def numSpecialEquivGroups(self, A) -> int:
s = set()
for S in A:
evens = tuple(sorted(Counter(S[0::2]).items()))
odds = tuple(sorted(Counter(S[1::2]).items()))
s.add((evens, odds))
return len(s)
if __name__ == '__main__':
s = Solution()
a = ["abcd", "cdab", "cbad", "xyzz", "zzxy", "zzyx"]
res = s.numSpecialEquivGroups(a)
print(res)