1. 程式人生 > >[leetcode]python3 演算法攻略-有效的字母異位詞

[leetcode]python3 演算法攻略-有效的字母異位詞

給定兩個字串 st ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。

方案一:s.count()比較各元素的個數

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return set(s) == set(t) and all(s.count(i) == t.count(i) for i in set(s))

方案二:利用Counter快速統計各元素的個數,但效率上比方案一低

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """        
        from collections import Counter
        return Counter(s) == Counter(t)