qtL0ng


私信TA

用户名:qtL0ng

访问量:4359

签 名:

等  级
排  名 6077
经  验 1401
参赛次数 0
文章发表 33
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

参考代码:

#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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区