題目:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
給定兩個字串,判斷一個字串是否由另一個字串重組而成
這題最簡單可以這樣解
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s)==sorted(t)
透過sorted讓字串用字元編碼排序
若t真的是由s重組而成,兩者排序後應該會一模一樣
最後執行時間50ms(faster than 91.32%)
當然一般還是建立hash map去解
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s)!=len(t):
            return False
        d1={}
        d2={}
        
        for i in range(len(s)):
            if s[i] in d1:
                d1[s[i]]=d1[s[i]]+1
            else:
                d1[s[i]]=1
                
            if t[i] in d2:
                d2[t[i]]=d2[t[i]]+1
            else:
                d2[t[i]]=1
                
        for i in d1:
            if i not in d2:
                return False
            else:
                if d1[i]!=d2[i]:
                    return False
                
        return True
為兩字串個別建立一個dictionary,紀錄各字元出現的次數
最後再比較兩dictionary所記錄的值是否相等
且確認一字串是否有另一字串沒有的字元
最後執行時間48ms(faster than 93.25%)
那我們下題見