Leetcode 893. Groups of Special-Equivalent Strings

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 893. Groups of Special-Equivalent Strings相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Groups of Special-Equivalent Strings

2. Solution

**解析:**Version 1,比较两个字符串的有序奇数位和有序偶数位,如果相等,则两个字符串属于同一组。Version 2,连接有序奇数位字符串和偶数位字符串,放入set中,返回set中的元素个数即可。

  • Version 1
class Solution:
    def numSpecialEquivGroups(self, words: List[str]) -> int:
        count = 0
        while words:
            count += 1
            group = []
            candidate = words[0]
            odd = sorted(candidate[::2])
            even = sorted(candidate[1::2])
            for index, word in enumerate(words):
                s1 = sorted(word[::2])
                s2 = sorted(word[1::2])
                if odd == s1 and even == s2:
                    group.append(index)
            for i in group[::-1]:
                words.pop(i)

        return count    
  • Version 2
class Solution:
    def numSpecialEquivGroups(self, words: List[str]) -> int:
        result = set()
        for word in words:
            odd_even = ''.join(sorted(word[::2])) + ''.join(sorted(word[1::2]))
            result.add(odd_even)
        return len(result)

Reference

  1. https://leetcode.com/problems/groups-of-special-equivalent-strings/

以上是关于Leetcode 893. Groups of Special-Equivalent Strings的主要内容,如果未能解决你的问题,请参考以下文章

893. Groups of Special-Equivalent Strings - LeetCode

Leetcode 893. Groups of Special-Equivalent Strings

893. Groups of Special-Equivalent Strings

[Solution] 893. Groups of Special-Equivalent Strings

leetcode 0216

Leetcode 830. Positions of Large Groups