Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โค้ด C++ หาสตริงพาลินโดรมที่มี S เป็น subsequence

โจทย์: สตริง S หาสตริง T ที่เป็นพาลินโดรม และ S เป็น subsequence ของ T

Input: S="ab" → Output: "aabaa" (คำตอบอื่นก็ได้ เช่น "abba")

ขั้นตอนแก้

res := S
reverse S
res := res + S
return res

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;
string solve(string S) {
    string res = S;
    reverse(S.begin(), S.end());
    res += S;
    return res;
}
int main() {
    string S = "ab";
    cout << solve(S) << endl;
}

Input

ab

Output

abba