1. 程式人生 > >【LeetCode 簡單題】66-有效的字母異位詞

【LeetCode 簡單題】66-有效的字母異位詞

宣告:

今天是第66道題。給定兩個字串 s 和 t ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

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

示例 1:

輸入:
s = "anagram", t = "nagaram" 輸出: true

示例 2:

輸入: s = "rat", t = "car"
輸出: false

說明:
你可以假設字串只包含小寫字母。

進階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?

解法1。先把字串強制轉換為list,再用內建排序函式sorted對list排序,然後直接比較2個list是否相等,程式碼如下。

執行用時: 64 ms, 在Valid Anagram的Python提交中擊敗了54.03% 的使用者

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        s_sorted = sorted(list(s))
        t_sorted = sorted(list(t))
        return s_sorted == t_sorted

 解法2。利用python靈活的語法,set、str、list之間可允許的強制轉換

執行用時: 36 ms, 在Valid Anagram的Python提交中擊敗了86.30% 的使用者

class Solution(object):
    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))

 解法2。和上一種解法異曲同工,更好理解一些,就是以t為比較基準,遍歷t中的每一個字元出現次數和s中的是否相等

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        t_set = set(t)
        for i in t_set:
            if s.count(i) != t.count(i):
                return False
        return True

結尾

解法1&解法2:https://blog.csdn.net/qq_34364995/article/details/80657927

解法3:LeetCode