Leetcode-有效字母異位詞
阿新 • • 發佈:2018-11-27
242.有效字母的異位詞
給定兩個字串 s 和 t ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。
示例 1:
輸入: s = “anagram”, t = “nagaram”
輸出: true
示例 2:
輸入: s = “rat”, t = “car”
輸出: false
思路:
第一種方法:排序
因為字母都是一樣的才行,那麼我們直接讓string字串按照順序排列下來,一樣的即可。很簡單。但是這裡時間複雜度最低也是NlogN,就算是快排。
第二種方法:Map:計數
{letter: Count}
Map -> Count {a:3, n:1…}
時間複雜度來看,這只是在計數,所以是O(N),如果再加上插入刪除和查詢,都是O(1),所以合起來也是O(N),所以這種方法略快於排序的演算法。
程式碼:
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # dic1, dic2 = {}, {} # for item in s: # dic1[item] = dic1.get(item, 0) + 1 # for item in t: # dic2[item] = dic2.get(item, 0) + 1 # return dic1 == dic2 dic1, dic2 = [0]*26, [0]*26 for item in s: dic1[ord(item)-ord('a')] += 1 #計數中~ for item in t: dic2[ord(item)-ord('a')] += 1 return dic1 == dic2