Original link: leetcode-cn.com/problems/va…

Answer:

  1. The number of letters in two strings is the same.
  2. Map is used to store the difference in the number of letters in a string, and if they all have a value of 0, they all have the same number of letters.
  3. Iterating over the string S, incrementing the quantity in the Map +1 for each letter encountered.
  4. Iterating through the string t, the quantity -1 in the Map is encountered for each letter.
/ * * *@param {string} s
 * @param {string} t
 * @return {boolean}* /
var isAnagram = function (s, t) {
  // The length of two strings is not equal, and the number of letters must not be equal
  if(s.length ! == t.length) {return false;
  }

  let map = {}; // Store the number of letters per letter

  // Count the number of letters in s
  for (const char of s) {
    map[char] ? map[char]++ : (map[char] = 1);
  }

  // Iterate over each letter of t
  for (const char of t) {
    // Map [char] is null or 0 when t and s are not equal
    if(! map[char]) {return false;
    }
    // Reduce the number of letters in the map
    map[char]--;
  }

  return true;
};
Copy the code