1. 程式人生 > >Leetcode刷題筆記python---有效的字母異位詞

Leetcode刷題筆記python---有效的字母異位詞

有效的字母異位詞

題目

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

示例 1:

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

輸入: s = “rat”, t = “car” 輸出: false 說明: 你可以假設字串只包含小寫字母。

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

解答

思路:

  1. 分解成list
  2. sort
  3. 比較

程式碼:

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
def splitstr(x): y=[] for i in range(len(x)): y.append(x[i]) return y s=splitstr(s) t=splitstr(t) s.sort() t.sort() if s==t: return True return False

結果:17%