「每日LeetCode」2021年8月28日

本文最后更新于:2023年3月19日 晚上

剑指 Offer II 032. 有效的变位词

剑指 Offer II 032. 有效的变位词

给定两个字符串 st ,编写一个函数来判断它们是不是一组变位词(字母异位词)。
注意:_s__t__ *中每个字符出现的次数都相同且字符顺序不完全相同,则称 \_s*_t__ _互为变位词(字母异位词)。
示例  1:

1
2
输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

1
2
输入: s = "rat", t = "car"
输出: false

示例 3:

1
2
输入: s = "a", t = "a"
输出: false

提示:

  • 1 <= s.length, t.length <= 5 * 10
  • s and t 仅包含小写字母

**进阶: **如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
注意:本题与主站 242  题相似(字母异位词定义不同):https://leetcode-cn.com/problems/valid-anagram/

思路

哈希表记录每个字母出现次数以后,逐个判断是否一致即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
if (s.length !== t.length || s === t) return false;
const getMap = (word) => {
const map = new Map();
for (const char of word)
map.set(char, map.has(char) ? map.get(char) + 1 : 1);
return map;
};
const mapS = getMap(s);
const mapT = getMap(t);
return [...mapS].every(([key, value]) => {
return mapT.get(key) === value;
});
};