
题目要求
You are given an array A
of strings.
Two strings S
and T
are special-equivalent if after any number of moves, S == T.
A move consists of choosing two indices i
and j
with i % 2 == j % 2
, and swapping S[i]
with S[j]
.
Now, a group of special-equivalent strings from A
is a non-empty subset S of A
such that any string not in S is not special-equivalent with any string in S.
Return the number of groups of special-equivalent strings from A
.
题目分析及思路
给定一组字符串,若经过若干次move两个字符串相等,则这两个字符串是special-equivalent。定义一次move是将字符串中的奇数或偶数位置的两个字母交换。题目要求返回这一组字符串的special-equivalent字符串的组数。可以分别对每一个字符串的奇数和偶数位置的字母进行排序再合并,最后将合并的结果放入集合中,集合的长度即为所求。
python代码
class Solution:
def numSpecialEquivGroups(self, A: 'List[str]') -> 'int':
s = set()
for a in A:
s.add(''.join(sorted(a[0::2]))+''.join(sorted(a[1::2])))
return len(s)