242. 有效的字母异位词
解法一:使用数组
function isAnagramArray(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}
const LOWERCASE_A_CODE = "a".charCodeAt(0); // 97
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - LOWERCASE_A_CODE]++;
count[t.charCodeAt(i) - LOWERCASE_A_CODE]--;
}
return count.every((val) => val === 0);
}
// 测试
console.log(isAnagramArray("anagram", "nagaram")); // 输出: true
console.log(isAnagramArray("rat", "car")); // 输出: false
解法二:使用哈希表(对象)
function isAnagramObject(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}
const charCount: { [key: string]: number } = {};
for (const char of s) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (const char of t) {
if (!charCount[char]) {
return false;
}
charCount[char]--;
if (charCount[char] < 0) {
return false;
}
}
return true;
}
// 测试
console.log(isAnagramObject("listen", "silent")); // 输出: true
console.log(isAnagramObject("hello", "world")); // 输出: false
console.log(isAnagramObject("aacc", "ccac")); // 输出: false
ts 简单解法
function isAnagram(s: string, t: string): boolean {
let ss = s.split("").sort().join("");
let ts = t.split("").sort().join("");
return ss == ts;
}