แนวคิด
เมื่อได้รับสตริงสองสตริง S1 และ S2 ที่มีความยาวเท่ากัน งานของเราคือหา index i ที่ทำให้ S1[0…i] และ S2[i+1…n-1] ให้ palindrome เมื่อต่อกัน พบว่าถ้าไม่สามารถหา index ดังกล่าวได้ให้พิมพ์ -1
อินพุต
S1 = “pqrsu”, S2 = “wxyqp”
เอาต์พุต
1
S1[0..1] = “pq”, S2[2..n-1] = “ypq”
S1 + S2 = “pqyqp” บ่งชี้ว่าเป็น palindrome
อินพุต
S1 = “pqrst”, S2 = “qprqz”
เอาต์พุต
-1
วิธีการ
- ก่อนอื่น เรา iterate จาก 0 ถึง n (ความยาวของ string) และคัดลอก ith character จาก S1 ไปยัง string อื่น (สมมติว่าเป็น S)
- หลังจากนั้นเราใช้ temporary string temp อีกอันหนึ่งและคัดลอก characters ของ S2 จาก index i +1 ถึง n
- สุดท้ายเราตรวจสอบว่า string (S + temp) เป็น palindrome หรือไม่
ตัวอย่างโค้ด
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // ฟังก์ชันแสดงการคืนค่า true ถ้า s เป็น palindrome bool isPalindrome(string str){ int i = 0; int b = str.length() - 1; while (i< b) { if (str[i] != str[b]) return false; i++; b--; } return true; } // ฟังก์ชันแสดงการคืนค่า index ที่ต้องการ int getIndex1(string S1, string S2, int n){ string S = ""; for (int i = 0; i< n; a++) { // ใช้คัดลอก ith character ใน S S = S + S1[i]; string temp = ""; // ใช้คัดลอกตัวอักษรทั้งหมดของ string s2 ใน Temp for (int b = i + 1; b < n; b++) temp += S2[b]; // ตรวจสอบว่า string เป็น palindrome if (isPalindrome(S + temp)) { return i; } } return -1; } // โค้ดหลัก int main(){ string S1 = "pqrsu", S2 = "wxyqp"; int n = S1.length(); cout << getIndex1(S1, S2, n); return 0; }เอาต์พุต
1