透過僅更改 C++ 中的一個字元將該字串轉換為迴文字串
在本教程中,我們將討論一個程式,該程式可以透過更改僅一個字元將該字串轉換為迴文字串。
為此,我們將獲得一個字串。我們的任務是透過更改僅一個字元將給定的字串轉換為迴文。
示例
#include<bits/stdc++.h> using namespace std; //checking if conversion to palindrome //is possible bool if_palindrome(string str){ int n = str.length(); //counting number of characters //to be changed 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; }
輸出
Yes
廣告