Palindrome คืออะไร?
String ที่อ่านจากหน้าหลังและหลังหน้า **เหมือนกัน** เช่น "racecar", "level", "madam"
อัลกอริทึม Two Pointers
forwardชี้ตัวแรก (Index 0)reverseชี้ตัวสุดท้าย (Index len-1)- While
forward < reverse:- ถ้า
*forward == *reverse→ ++forward, --reverse - Else → ไม่ใช่ Palindrome → Break
- ถ้า
- จบ Loop → เป็น Palindrome
ตัวอย่างโปรแกรม
#include <stdio.h>
#include <string.h>
int isPalindrome(const char *str) {
const char *forward = str;
const char *reverse = str + strlen(str) - 1;
while (forward < reverse) {
if (*forward != *reverse)
return 0; // False
forward++;
reverse--;
}
return 1; // True
}
int main() {
char str[] = "racecar";
printf("'%s' is palindrome: %s\n", str, isPalindrome(str) ? "Yes" : "No");
char str2[] = "hello";
printf("'%s' is palindrome: %s\n", str2, isPalindrome(str2) ? "Yes" : "No");
return 0;
}
ผลลัพธ์:
'racecar' is palindrome: Yes
'hello' is palindrome: No
ตัวอย่างที่ 2: รับ Input จาก User
#include
#include
#include
// ตรวจสอบ Palindrome ไม่สนใจ Case และ Non-alphanumeric
int isPalindromeAdvanced(const char *str) {
const char *left = str;
const char *right = str + strlen(str) - 1;
while (left < right) {
// ข้าม Non-alphanumeric
while (left < right && !isalnum((unsigned char)*left)) left++;
while (left < right && !isalnum((unsigned char)*right)) right--;
if (left >= right) break;
// เปรียบเทียบ Case-insensitive
if (tolower((unsigned char)*left) != tolower((unsigned char)*right))
return 0;
left++;
right--;
}
return 1;
}
int main() {
char input[100];
printf("Enter string: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
if (isPalindromeAdvanced(input))
printf("'%s' is a Palindrome!\n", input);
else
printf("'%s' is NOT a Palindrome.\n", input);
return 0;
}
ผลลัพธ์ตัวอย่าง:
Enter string: A man, a plan, a canal: Panama
'A man, a plan, a canal: Panama' is a Palindrome!
Enter string: Hello World
'Hello World' is NOT a Palindrome.
Complexity
- Time: O(n) - เดินผ่าน String ครั้งเดียว
- Space: O(1) - ใช้ Pointer 2 ตัวเท่านั้น
ข้อได้เปรียบของ Two Pointer Technique
- ไม่ต้องสร้าง String ใหม่ (Reverse Copy)
- Memory Efficient
- Early Exit เมื่อเจอตัวไม่ตรง
- เข้าใจง่าย ใกล้กับ Logic มนุษย์