ภาพรวม
บทความนี้สาธิตวิธีหาตัวอักษรที่หายไปจากสตริงที่ควรจะมีตัวอักษร a-z ครบ (หรือ a-m ฯล฿) โดยสตริงจะขาดตัวอักษรไป 1 ตัว
ตัวอย่าง
const str = "acdghfbekj"; // ขาด 'i'
การนำไปใช้
const missingCharacter = (str) => {
const s = str.toLowerCase();
for (let i = 97; ; i++) { // 97 = 'a' char code
if (s.includes(String.fromCharCode(i))) {
continue;
}
return String.fromCharCode(i);
}
return false;
};
console.log(missingCharacter(str)); // 'i'
ผลลัพธ์
i
วิธีการที่มีประสิทธิภาพมากกว่า (O(n) แทน O(n×alphabet))
const missingCharacterFast = (str) => {
const seen = new Set(str.toLowerCase());
for (let i = 97; i <= 122; i++) { // a-z
if (!seen.has(String.fromCharCode(i))) {
return String.fromCharCode(i);
}
}
return null; // ไม่มีตัวไหนหาย (ครบทุกตัว)
};
วิธีการทางคณิตศาสตร์ (XOR / Sum)
// ใช้ XOR (เหมาะสำหรับขาดเพียง 1 ตัว)
const missingCharXOR = (str) => {
let xor = 0;
// XOR ของ a-z ทั้งหมด
for (let i = 97; i <= 122; i++) xor ^= i;
// XOR กับตัวอักษรในสตริง
for (const char of str.toLowerCase()) xor ^= char.charCodeAt(0);
return String.fromCharCode(xor);
};
// ใช้ Sum
const missingCharSum = (str) => {
const total = (97 + 122) * 26 / 2; // Sum of a-z = 2574
const sum = [...str.toLowerCase()].reduce((s, c) => s + c.charCodeAt(0), 0);
return String.fromCharCode(total - sum);
};
การขยาย: หาตัวอักษรที่หายหลายตัว
const missingCharacters = (str, startChar = 'a', endChar = 'z') => {
const seen = new Set(str.toLowerCase());
const missing = [];
for (let i = startChar.charCodeAt(0); i <= endChar.charCodeAt(0); i++) {
if (!seen.has(String.fromCharCode(i))) {
missing.push(String.fromCharCode(i));
}
}
return missing;
};
console.log(missingCharacters('abcef')); // ['d']
console.log(missingCharacters('aceg')); // ['b', 'd', 'f']
การประยุกต์ใช้
- Data Validation: ตรวจสอบลำดับ Serial Number
- Puzzle Games: Word Games, Crosswords
- Cryptography: Frequency Analysis
- Database: หา Missing Sequence Numbers