leetcode-有效的字母異位詞

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

示例 1:

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

示例 2:

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

說明:
你可以假設字符串只包含小寫字母。

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

代碼

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    let a ={};
    let result = true;
    for(let i=0;i<s.length;i++){
        a[s[i]] == null?a[s[i]] = 1 : a[s[i]] ++;
        
    }
    
    for(let i=0;i<t.length;i++){
        if(!a[t[i]]){
            return false;
        }else{
            a[t[i]] --;
        }
    }
    
    for(let key in a){
        if(a[key] !=0){
            return false;
        }
    }
    
    return true;
    
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章