อะนาก램 (Anagrams)
อะนาก램 คือคู่สตริง ซึ่งหนึ่งในสองตัวเมื่อจัดเรียงใหม่ในรูปแบบหนึ่ง จะได้อีกตัวหนึ่ง
เช่น 'hello' และ 'lolhe' เป็นอะนาก램 เพราะเราสามารถจัดเรียง 'lolhe' ใหม่เพื่อสร้างสตริง 'hello' หรือในทางกลับกัน
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองสตริง สมมติว่า str1 และ str2 ฟังก์ชันควรคืนค่า true ถ้าสตริงเป็นอะนาก램ของกันและกัน false ถ้าไม่ใช่
เราสามารถสร้างแผนที่ที่นับจำนวนตัวอักษรสำหรับแต่ละสตริงอินพุต แล้วเราสามารถเปรียบเทียบแผนที่เพื่อดูว่ามันเหมือนกันหรือไม่
ตัวอย่าง
const str1 = 'hello';
const str2 = 'lolhe';
const charCount = string => {
const table = {};
for (let char of string.replace(/\W/g, "").toLowerCase()) table[char] = table[char] + 1 || 1;
return table;
};
const anagrams = (stringA, stringB) => {
const charCountA = charCount(stringA);
const charCountB = charCount(stringB);
if (Object.keys(charCountA).length !== Object.keys(charCountB).length)
return false;
for (let char in charCountA)
if (charCountA[char] !== charCountB[char])
return false;
return true;
};
console.log(anagrams(str1, str2));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
true