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

  // Use Map to store the number of letters
  let map = new Map(a);for (let i = 0; i < s.length; i++) {
    const sChar = s[i]; // The letters in the string s
    const tChar = t[i]; // The letter in the string t

    // As each letter in s is iterated, the quantity in the Map is +1
    typeof map.get(sChar) === 'number'
      ? map.set(sChar, map.get(sChar) + 1)
      : map.set(sChar, 1); // Set the initial value of the map

    // As each letter in t is iterated, the quantity in the Map is -1
    // After traversal, if the number of letters in the two strings is equal, the value stored in the Map is 0
    typeof map.get(tChar) === 'number'
      ? map.set(tChar, map.get(tChar) - 1)
      : map.set(tChar, -1); // Set the initial value of the map
  }

  // Iterate over the number of letters stored in the Map
  for (const [name, number] of map) {
    // If the number of characters is not 0, the number of characters in the two strings is not equal
    if (number > 0) {
      return false; }}// If you exit for... The of loop, which indicates that two strings have the same number of letters
  return true;
};
Copy the code