codeforces 363C Fixing Typos

来源:互联网 发布:程序员平均年薪40万 编辑:程序博客网 时间:2024/06/02 03:28

C. Fixing Typos
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Many modern text editors automatically check the spelling of the user’s text. Some editors even suggest how to correct typos.

In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word “helllo” contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words “helloo” and “wwaatt” contain typos).
Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
Input
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
Output
Print such word t that it doesn’t contain any typos described in the problem statement and is obtained from s by deleting the least number of letters.
If there are multiple solutions, print any of them.
Examples
input
helloo
output
hello
input
woooooow
output
woow
Note
The second valid answer to the test from the statement is “heloo”.
题意: 处理字符串,两种情况,1不能连续出现三次以上的字母 2两个两个相同的字母不能出现 ,即AABB模式
思路:一开始想到去模拟这个过程,在输出的时候进行判断,用到了26 长度的数组,和last标记上一个输出的字母,仔细一想,就是栈的思想。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;char line[200005];char stack[200005]; int main(){    int top=0;     scanf("%s",line);     stack[top++] = line[0];     stack[top++] = line[1];      int len = strlen( line ) ;     for ( int i=2; i<len; i++ )  {        if ( line[i]==stack[top-1] && line[i]==stack[top-2] ) continue;        else if ( line[i]==stack[top-1] && stack[top-3]==stack[top-2] ) continue;         else stack[top++] = line[i];      }    stack[top] = '\0'; //没有处理长度是1的时候的换行    printf("%s",stack);     return 0; }  

第二种解法是 用两个数组记录,1记录出现的字母的数组,2记录字母的连续次数
对连续次数进行处理,大于2 处理为2,两个2连续的其中一个置1

#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>using namespace std; char line[200005]; char last[200005];int num[200005];int main(){    int deal;     scanf("%s",line);     int len = strlen( line );    int cnt=0;    last[cnt] = line[0];     ++num[cnt];    for (int i=1;i<len; i++ ) {        if ( line[i]==last[cnt] ) ++num[cnt];         else {            ++cnt;             last[cnt] = line[i];             ++num[cnt];         }     }    deal = cnt;     for ( int i=0; i<=deal ; i++ )         if ( num[i]>=3 ) num[i] = 2;     for ( int i=1; i<=deal ; i++ )         if ( num[i]==2&&num[i-1]==2 ) num[i] = 1;     for ( int i=0; i<=deal; i++  ) {        for ( int j=1;j<=num[i] ; j++ ) {            printf("%c",last[i]);         }    }    return 0; }
0 0
原创粉丝点击