C++程式查詢string在新增字元'a'後使得string為非迴文串
假設我們有一個字串S,其中包含小寫英文字母。我們必須在一個字元'a'中插入S。在插入之後,如果我們可以使S不是迴文,則返回該字串,否則返回“impossible”。
因此,如果輸入類似於S =“bpapb”,那麼輸出將為“bpaapb”。
步驟
要解決這個問題,我們將遵循以下步驟-
if concatenation of S and "a" is not palindrome, then: return S concatenation 'a' otherwise when concatenation of "a" + S is not palindrome, then: return 'a' concatenation S Otherwise return "Impossible"
示例
讓我們看看以下實現以獲得更好的理解 -
#include <bits/stdc++.h> using namespace std; bool p(const string& s) { for (int i = 0; i < s.size() / 2; i++) if (s[i] != s[s.size() - 1 - i]) return false; return true; } string solve(string S) { if (!p(S + 'a')) return S + 'a'; else if (!p('a' + S)) return 'a' + S; else return "Impossible"; } int main() { string S = "bpapb"; cout << solve(S) << endl; }
輸入
"bpapb"
輸出
bpapba
廣告