1. 程式人生 > >leetcode-有效的字母異位詞

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; };