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)