[LeetCode][JavaScript]Valid Anagram
Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
https://leetcode.com/problems/valid-anagram/
判断字符串t是不是由s交换顺序之后得到的。
开一个哈希表,记录出现的次数。
如果长度不同,直接返回false,这样就避免了最后还要遍历一把哈希表。
1 /** 2 * @param {string} s 3 * @param {string} t 4 * @return {boolean} 5 */ 6 var isAnagram = function(s, t) { 7 if(s.length !== t.length){ 8 return false; 9 } 10 var i, dict = {}; 11 for(i = 0; i < s.length; i++){ 12 if(!dict[s[i]]){ 13 dict[s[i]] = 1; 14 }else{ 15 dict[s[i]]++; 16 } 17 } 18 for(i = 0; i < t.length; i++){ 19 if(!dict[t[i]] || dict[t[i]] === 0){ 20 return false; 21 }else{ 22 dict[t[i]]--; 23 } 24 } 25 return true; 26 };