異位詞

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

若 s 和 t 中每個字符出現的次數都相同,則稱 s 和 t 互爲字母異位詞

輸入:s = "anagram" t = "nagram" 輸出:False

輸入:s = "anagram" t = "anagram" 輸出:True

def isAnagram(s1, s2):
    return Counter(s1)==Counter(s2)
 
def isAnagram(s1, s2):
    return sorted(s1)==sorted(s2)
 
def isAnagram(s, t):
    s_c, t_c = {}, {}
    for k in s:
        if k not in s_c.keys():
            s_c[k] = 1
        else:
            s_c[k] += 1
    for kk in t:
        if kk not in t_c.keys():
            t_c[kk] = 1
        else:
            t_c[kk] += 1
    return s_c==t_c

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章