52 lines
1.6 KiB
JavaScript
52 lines
1.6 KiB
JavaScript
/**
|
||
* https://leetcode.cn/problems/valid-anagram/?envType=study-plan-v2&envId=top-interview-150
|
||
* @param {string} s
|
||
* @param {string} t
|
||
* @return {boolean}
|
||
*/
|
||
const isAnagram = function (s, t) {
|
||
|
||
};
|
||
|
||
/*
|
||
判断s是否是t的异位词,异位词就是重新排列字符顺序的词就是异位词,所以异位词的长度和原本单词的长度一致,同一个字符出现的次数也一致
|
||
题目的输入只包含26个小写字母,所利用数组的下标表示t中出现的小写字母,值为出现的次数,之后遍历s,s中的每个单词会使其对应的计数减少
|
||
1,如果出现某个计数小于0直接返回false
|
||
*/
|
||
function f1(s, t) {
|
||
if (s.length !== t.length) return false;
|
||
// 统计t中字母出现的频次
|
||
const charCounts = new Array(26).fill(0);
|
||
for (let i = 0; i < t.length; i++) {
|
||
charCounts[t.charCodeAt(i) - 97]++;
|
||
}
|
||
|
||
for (let i = 0; i < s.length; i++) {
|
||
const index = s.charCodeAt(i) - 97;
|
||
charCounts[index]--;
|
||
if (charCounts[index] < 0) return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/*
|
||
处理unicode字符,js中有一个坑,使用t[i]取unicode字符时,如果这个字符是一个代理对,比如emjoy表情,就会使用两个unicode16表示
|
||
所以应该使用for of来处理,应该字符串本身就是一个可迭代对象,底层会保证它返回的字符是正确的
|
||
*/
|
||
function f2(s, t) {
|
||
if (s.length !== t.length) return false;
|
||
|
||
const map = new Map();
|
||
for (const ch of t) {
|
||
map.set(ch, (map.get(ch) || 0) + 1);
|
||
}
|
||
|
||
for (const ch of s) {
|
||
if (!map.has(ch)) return false;
|
||
map.set(ch, map.get(ch) - 1);
|
||
if (map.get(ch) < 0) return false;
|
||
}
|
||
|
||
return true;
|
||
}
|