chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:242. 有效的字母异位词,哈希表两次循环,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:https://leetcode-cn.com/problems/valid-anagram/

解题思路:

  1. 该题实际要对比的是两个字符串中的每个字母的数量是否相同。
  2. 使用Map存储字符串中的字母数量之差,如果其值都为0,则表示字母数量都相同。
  3. 遍历字符串s,遇到每个字母时,都将Map中的数量+1。
  4. 遍历字符串t,遇到每个字母时,都将Map中的数量-1。
/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function (s, t) {
  // 两个字符串的长度不相等,其中的各个字母数量必然不相等
  if (s.length !== t.length) {
    return false;
  }

  let map = {}; // 存储每个字母数量

  // 统计s中的每个字母数量
  for (const char of s) {
    map[char] ? map[char]++ : (map[char] = 1);
  }

  // 遍历t的每个字母
  for (const char of t) {
    // 只要s和t中的部分字母数量不相等,遍历t时,就会遇到map[char]为空或为0的情况
    if (!map[char]) {
      return false;
    }
    // 减少map中的字母数量
    map[char]--;
  }

  return true;
};