algorighm/top-interview-leetcode150/hash-table/242有效的字母异位词.js

52 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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中出现的小写字母值为出现的次数之后遍历ss中的每个单词会使其对应的计数减少
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;
}