(每日一題!!)LeetCode:242. 有效的字母異位詞。。。

題目

  1. 有效的字母異位詞
    給定兩個字符串 s 和 t ,編寫一個函數來判斷 t 是不是 s 的字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:
輸入: s = "rat", t = "car"
輸出: false
說明:
你能夠假設字符串只包含小寫字母。
進階:
若是輸入字符串包含 unicode 字符怎麼辦?你可否調整你的解法來應對這種狀況?

1、解題思路1

直接用sorted()函數排完序進行比較。python

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

運行結果

2、解題思路2

用Python的collections內置模塊進行判斷。web

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return collections.Counter(s) == collections.Counter(t)

運行結果

3、解題思路3

先用集合去重,在遍歷每一個字母的個數,若是每一個都相等則爲True,不然爲False。svg

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        set1 = set(s)
        for i in set1:
            if s.count(i) != t.count(i):
                return False
        return True

運行結果

本文分享 CSDN - Kinght_123。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。函數

相關文章
相關標籤/搜索