เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเป็นอาร์กิวเมนต์เดียว ภารกิจคือตรวจสอบว่าการจัดเรียงใหม่ของตัวอักษรในสตริงสามารถให้สตริงพาลินโดรมได้หรือไม่ ถ้าได้คืน true มิฉะนั้น false
ตัวอย่าง
ถ้าสตริงนำเข้าคือ:
const str = 'amadm';
ผลลัพธ์ควรเป็น:
const output = true;
เพราะสตริงสามารถจัดเรียงใหม่เป็น 'madam' ซึ่งเป็นพาลินโดรม
ตัวอย่างโค้ด
const str = 'amadm';
const canFormPalindrome = (str = '') => {
const hash = {};
let count = 0;
for (let i = 0; i < str.length; i++) {
let c = str[i];
if(c === ' ') {
continue;
}
if(hash[c]) {
delete hash[c];
} else {
hash[c] = true;
}
count++;
}
if(count % 2 === 0) {
return Object.keys(hash).length === 0;
} else {
return Object.keys(hash).length === 1;
}
};
console.log(canFormPalindrome(str));
ผลลัพธ์
true