字符串处理算法(八)将字符串中连续出席的重复字母进行压缩(华为校园招聘题)
一、题目要求
通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1、仅压缩连续重复出现的字符。比如字符串”abcbc”由于无连续重复字符,压缩后的字符串还是”abcbc”。
2、压缩字段的格式为”字符重复的次数+字符”。例如:字符串”xxxyyyyyyz”压缩后就成为”3x6yz”。
要求实现函数:
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
输入pInputStr: 输入字符串lInputLen: 输入字符串长度
输出 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
注意:只需要完成该函数功能算法,中间不需要有任何IO的输入输出
示例
输入:“cccddecc” 输出:“3c2de2c”
输入:“adef” 输出:“adef”
输入:“pppppppp” 输出:“8p”
二、代码实现
1、算法一
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr){int i = lInputLen-1,j=0;char last = pInputStr[i],curr;int count = 1;for(i = i-1; i>=0; i--){curr = pInputStr[i];if(last == curr){count++;}else{pOutputStr[j++] = last;if(count>1)pOutputStr[j++] = '0' + count;count = 1;}last = curr;}if(count >1){pOutputStr[j++] = last;pOutputStr[j++] = '0' + count;}elsepOutputStr[j++] = last;int nLen = strlen(pOutputStr);for(i = 0;i<nLen/2;i++){pOutputStr[i] = pOutputStr[nLen-i-1] + pOutputStr[i];pOutputStr[nLen-i-1] = pOutputStr[i] - pOutputStr[nLen-i-1];pOutputStr[i] = pOutputStr[i] - pOutputStr[nLen-i-1];}}
这个算法的思路是从后往前遍历进行统计个数,当遇到不是相同字符的时候,就往输出串里赋值,然后对输出串进行前后交换。但是这里有一个比较严重的问题就是,当cout大于10之后,就得不到正确的值。
2、算法二
void stringZipEx(const char *pInputStr, long lInputLen, char *pOutputStr){int i = lInputLen-1,j=0;char last = pInputStr[i],curr;string strCur="";string StrAll="";char strTemp[8];int count = 1;for(i = i-1; i>=0; i--){curr = pInputStr[i];if(last == curr){count++;}else{if(count>1)strCur = itoa(count, strTemp, 10);strCur += last;strCur += StrAll;StrAll = strCur;strCur="";count = 1;}last = curr;}if(count>1)strCur = itoa(count, strTemp, 10);strCur += last;strCur += StrAll;StrAll = strCur;strcpy(pOutputStr, StrAll.c_str());}
这个算法的思路是从后往前遍历进行统计个数,当遇到不是相同字符的时候,就往strCur里赋值,处理后然后赋值给strAll。最后再copy到输出串。
转载请注明原创链接:http://blog.csdn.net/wujunokay/article/details/13298577