欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C.Good String

程序员文章站 2024-03-05 18:05:43
...

            Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings goodstring and xyyx are good strings, and the strings badaa and aabc are not good. Note that the empty string is considered good.

You are given a string ss, you have to delete minimum number of characters from this string so that it becomes good.

Input

The first line contains one integer n (1n≤2⋅105) — the number of characters in s.

The second line contains the string s, consisting of exactly n lowercase Latin letters.

Output

In the first line, print one integer k (0≤kn) — the minimum number of characters you have to delete from ss to make it good.

In the second line, print the resulting string sIf it is empty, you may leave the second line blank, or not print it at all.

tC.Good String 

题意: 给出字符串的长度和字符串。要求第一个字符和第二个字符不同,第三个和第四个不同......以此类推到第n-1和第n个字符不同,要求字符串的长度最后一定为偶数。求删除字符使其满足的最少次数和得到的字符串。

思路:因为要求最后n一定为偶数,所以从右端点向左遍历一遍,如果有相同的就进行修改,跳一个单位;如果不同,不操作,跳两个单位。到最后,判断一下剩下的字符是否为奇数,若为奇数,则第一个字符删掉。具体看下面代码,很简单。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
char c[202000];
int main()
{
    int n,x,i,sum=0;
    scanf("%d",&n);
    scanf("%s",c+1);
    for(i=n;i>1;)
    {
        if(c[i]==c[i-1])
        c[i]='0',i=i-1,sum++;//相同使c[i]为'0',sum++,记录删除的次数;
        else
        i=i-2;//如果不同的话,i直接减两个单位;
    }
    if((n-sum)%2==0)//n-sum为剩下的字符串长度,判断是否为偶数
    {
        printf("%d\n",sum);
        for(i=1;i<=n;i++)
        if(c[i]!='0')
        printf("%c",c[i]);
    }
    else//如果不为偶数,就删除第一个字符,从第二个字符开始输出
    {
        printf("%d\n",sum+1);
        for(i=2;i<=n;i++)
        if(c[i]!='0')
        printf("%c",c[i]);
    }
    return 0;
}