JZX轻语:简
LeetCode 893 - 特殊等价字符串组
发表于2024年05月21日
可以通过观察发现,每个等价字符串组里面的字符串都满足一个特征:对其里面的字符按奇数位、偶数位分别排序,所得到的字符串都是一样的,而不同的组根据上述步骤所得到的特征字符串不一样。因此,可以使用一个set
记录不同的特征,返回集合的大小即可。
class Solution:
def numSpecialEquivGroups(self, words: List[str]) -> int:
# 每组都满足一个特征: 偶数位排序+奇数位排序后的字符串都是一样的
unique_pattern_set = set()
for word in words:
pattern = ''.join(sorted(word[::2]) + sorted(word[1::2]))
unique_pattern_set.add(pattern)
return len(unique_pattern_set)