字符串处理--HDU第1020题解题报告

来源:互联网 发布:淘宝运营培训费用 编辑:程序博客网 时间:2024/04/28 13:12

题目链接


首先想到是是用string类来做,但是string类好像不支持sprintf函数,所以改用C语言中的字符串来处理。至于为什么要用sprinf,等下解释。


该题的思路是找出相邻相等的字符,然后统计个数,把个数写进字符串中,然后删除多余的字符,但是删除麻烦,就用惰性删除的方法(不知道在哪看到的这个名词)

如果相同字符的个数小于10时,可以直接赋值写进字符串 str[index1]=_count; 

但是如果大于10,就不好了弄了,所以我用了sprintf函数实现。


下面是实现代码:


#include<iostream>#include<cstring>#include<cstdio>using namespace std;void encode(char *str,int length);int main(){    int n;    int length;    int i;    char str[11111];    cin>>n;    while(n--)    {        cin>>str;        length = strlen(str);        encode(str,length);        for(i=0;i!=length;i++)        {            if(str[i]!=7)//7是惰性标志                cout<<str[i];        }        cout<<endl;    }}void encode(char *str,int length){    int index1;     int index2;    char ch;//将字符赋给它    int _count;    for(index1=0;index1!=length;index1++)    {        _count = 0;        index2 = index1;        ch = str[index1];        while(ch == str[index2])        {            index2++;            _count++;//统计相同字符的个数        }        if(_count == 1)//如果为1,就继续            continue;        else if(_count == 2)//如果为2,不能用sprintf函数,例如:AA   那么sprintf会写入  2'\0',所以不可行        {            str[index1] = '2';            index1+1;//跳过        }        else        {            sprintf(str+index1,"%d",_count);//str[index1] = 48+count; error            index2 -=2;//减2,            while(str[index2]!=0)//从后往前惰性删除            {                str[index2] = 7;                index2--;            }str[index2] = 7;//将0结束标志覆盖掉            index1= index1 +_count -1;//跳过        }    }}


表达能力真是不行,希望能通过写博客改善。

愿得一学霸,带我刷刷题。


0 0
原创粉丝点击