C. Good String
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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 good, stringand xyyx are good strings, and the strings bad, aa 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 (1≤n≤2⋅1051≤n≤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≤k≤n0≤k≤n) — the minimum number of characters you have to delete from s to make it good.
In the second line, print the resulting string s. If it is empty, you may leave the second line blank, or not print it at all.
Examples
input
Copy
4 good
output
Copy
0 good
input
Copy
4 aabc
output
Copy
2 ab
input
Copy
3 aaa
output
Copy
3
题意:题目中规定合格的字符串的标准:1,长度为偶数 2,字符串奇数位和下一位即偶数位数字不能相等。求在原字符串中最少删除几个字符使其成为符合要求的字符串。
我的代码:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
stack<char>s;
char a[400005];
stack<char>ch;
void prtstk(){
while(!s.empty()){
ch.push(s.top());
s.pop();
}
while(!ch.empty()){
cout<<ch.top();
s.push(ch.top());
ch.pop();
}
cout<<endl;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
while(!s.empty())
{
s.pop();
}
while(!ch.empty())
{
ch.pop();
}
scanf("%s",a);
int len = strlen(a);
for(int i=0;i<len;i++)
{
if(i == 0)
{
s.push(a[i]);
}
else
{
if(s.size()%2==0)
{
s.push(a[i]);
}
else
{
if(s.top()!=a[i])
{
s.push(a[i]);
}
}
}
}
if(s.size()%2==1)
{
printf("%d\n",n-s.size()+1);
s.pop();
if(s.size()!=0)
{
prtstk();
}
}
else
{
printf("%d\n",n-s.size());
if(s.size()!=0)
{
prtstk();
}
}
}
return 0;
}
容易错的样例:
输入
4
gdoo
5
aaaaa
5
aabba
输出
gd
(为空串)
abba