LeetCode题解:242. 有效的字母异位词,数组计数,JavaScript,详细注释
chencl1986 opened this issue · comments
Lee Chen commented
原题链接:https://leetcode-cn.com/problems/valid-anagram/
解题思路:
- 该题实际要对比的是两个字符串中的每个字母的数量是否相同。
- 使用数组存储字符串中的字母数量之差,如果其值都为0,则表示字母数量都相同。
- 数组长度为26,按顺序对应了每个英文字母,index值由char.codePointAt(0) - 'a'.codePointAt(0)计算而来。
- 遍历字符串s,遇到每个字母时,都将数组中的数量+1。
- 遍历字符串t,遇到每个字母时,都将数组中的数量-1。
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
// 两个字符串的长度不相等,其中的各个字母数量必然不相等
if (s.length !== t.length) {
return false;
}
let arr = []; // 存储每个字母数量
// 统计s中的每个字母数量
for (const char of s) {
// 计算两个字母的码点之差,即为0-25的数字
const index = char.codePointAt(0) - 'a'.codePointAt(0);
arr[index] ? arr[index]++ : (arr[index] = 1);
}
// 遍历t的每个字母
for (const char of t) {
// 只要s和t中的部分字母数量不相等,遍历t时,就会遇到map[char]为空或为0的情况
const index = char.codePointAt(0) - 'a'.codePointAt(0);
if (!arr[index]) {
return false;
}
// 减少map中的字母数量
arr[index]--;
}
return true;
};