CodeForces - 600C Make Palindrome 贪心

A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.

You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters ins. Then you can permute the order of letters as you want. Permutation doesn't count as changes.

You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.

Input

The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.

Output

Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.

Example
Input
aabc
Output
abba
Input
aabcd
Output
abcba

题目大意:输入一串字符串,改变其中的字母或调整顺序,最后使得输出的字符串为字典序最小的回文,且要求变换次数最小(调准顺序不算)

思路:先使用一个数组,用来记录每个字符出现的次数,再用一个数组来记录个数为奇数的字母,然后从头尾两端向中间遍历,大的减一小的加一。最后再看为奇数字母的个数,若为偶数则按字母从小到大排序即可,若为奇数,则把最后为奇数个的字母放在中间,其余的按从小到大排序。

#include<stdio.h>
#include<string.h>
char str[200000];
int main()
{
	int n = 0;
	int re[26] = { 0 }, ch[26] = {0};
	
	int len;
	scanf("%s",str);
	len = strlen(str);
	for (int i = 0; i < len; i++)
	{
		re[str[i]-'a']++;
	}
	for (int i = 0; i < 26; i++)
	{
		if (re[i] % 2 != 0)
		{
			ch[n++] = i;
		}
	}
	for (int i = 0, j = n-1; i < j; i++, j--)
	{
		re[ch[i]]++;
		re[ch[j]]--;
	}
	if (n % 2 != 0)
	{
		str[len / 2] = ch[n / 2] + 'a';
	}
	for (int i = 0, j = len-1,h=0; i <= j; i++, j--)
	{
		for (; h < 26; h++)
		{
			if (re[h] >= 2)
			{
				re[h] -= 2;
				str[i] = h+'a';
				str[j] = h+'a';
				break;
			}
		}
	}
	printf("%s", str);

	return 0;
}


转载于:https://www.cnblogs.com/csu-lmw/p/9124469.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值