天天看點

LeetCode 242. 有效的字母異位詞

題目

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

示例 1:

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

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

說明:

你可以假設字元串隻包含小寫字母。

進階:

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

解題思路

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # #排序
        # sList = list(s)
        # tList = list(t)
        # sList.sort()
        # tList.sort()
        # if sList == tList:
        #     return True
        # return False
        #remove内置函數實作
        if len(s) > len(t):
            s, t = t, s #保證s長度最短
        tList = list(t)
        for i in s:
            print(tList)
            try:
                tList.remove(i)
            except:
                return False
        if len(tList) >0:
            return False
        else:
            return True           

繼續閱讀