ภาพรวมปัญหา
ตรวจสอบว่าสตริงสามารถกลายเป็น Palindrome ได้โดยเปลี่ยนตัวอักษรได้สูงสุด 1 ตัว
ตัวอย่าง
Input: "abccaa" Output: Yes
วิธีแก้ปัญหา
นับจำนวนคู่ตัวอักษรที่ไม่ตรงกัน (i และ n-i-1) ถ้า ≤ 1 → เป็นไปได้
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
bool if_palindrome(string str) {
int n = str.length();
int count = 0;
for (int i = 0; i < n / 2; ++i)
if (str[i] != str[n - i - 1])
++count;
return (count <= 1);
}
int main() {
string str = "abccaa";
if (if_palindrome(str))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
ผลลัพธ์ (Output)
Yes