参考代码:
#include<iostream> #include<string> #include<algorithm> using namespace std; void swap(char &s1, char &s2) { char t = s1; s1 = s2; s2 = t; } int main() { int n; //字符长度 string str, s; int i, j, p , flag = 0, count = 0; cin >> n >> str; int len = str.length(); //等于n for (i = 0;i < (len - 1) / 2;i++) { for (j = len - i - 1 + flag;j > i;j--) { if (str[i] == str[j]) { while (str[i] != str[len - i - 1 + flag]) { swap(str[j + 1], str[j]); //交换相邻的字符 j++, count++; } break; } } if (i == j) { //存在不成对的单个字符 flag = 1; p = i; } } if (flag) { //最后将单个字符移到中间位置 for (p;p < (len - 1) / 2;p++) { swap(str[p + 1], str[p]); count++; } } s = str; reverse(str.begin(), str.end()); if (s != str) { //如果移位后的字符串和倒序后该字符串不相等,则说明不能构成回文串 cout << "Impossible" << endl; return 0; } cout << count << endl; return 0; }
0.0分
7 人评分