跳到正文

题解

题解:P12592 重生有惊喜

cjy0329约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年5月24日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 2 分钟
获赞
4
题目
P12592

版本

  1. v1当前

重生有惊喜题解

前言

本蒟蒻花了一小时才切出来。

题意

一个字符串,交换一些字符,判断能否使其变成回文串。

分析

因为交换次数不限,所以相当于把字符串的顺序改变(打乱)。

回文串分为奇回文和偶回文。

我们定义奇回文,除了中间一项,其他都能左右两两配对,如:

acdca\color{red}\texttt{a}\color{blue}\texttt{c}\color{green}\texttt{d}\color{blue}\texttt{c}\color{red}\texttt{a}

我们定义偶回文,每个字符都能左右两两配对,如:

acddca\color{red}\texttt{a}\color{blue}\texttt{c}\color{green}\texttt{d}\color{green}\texttt{d}\color{blue}\texttt{c}\color{red}\texttt{a}

对于奇回文,有一种字符数量为奇数,其他字符的数量都为偶数;

对于偶回文,所有字符数量都为偶数。

代码

C++
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
string s;
int num[999];                  //统计字符数量
int doing() {
	memset(num, 0, sizeof num);//多组数据,初始化
	cin >> s;
	for (int i = 0; i < s.size(); i++) {
		int now = s[i];        //当前字符
		num[now]++;            //该字符数量+1
	}
	int ans = 0;
	for (int i = 'a'; i <= 'z'; i++) {
		if (num[i] & 1)
			ans++;             //统计无法配对字符的数量
	}
	if (s.size()&1){		   //长度为奇数,奇回文
		if(ans==1)puts("Yes");
		else puts("No");
	}else{                     //长度为偶数,偶回文
		if(ans==0)puts("Yes");
		else puts("No");
	}
	return 0;
}
int main() {
	int t;
	cin >> t;
	while (t--)doing();        //多组数据
	return 0;
}
原文
存档评论4 条抓取于