华为机试——字符串压缩字符串压缩通过键盘输入一串小写字母 a z 组成的字符串 请编写一个字符串压缩程序 将字符串中连续出席的重复字母进行压缩 并输出压缩后的字符串 压缩规则 1 仅压缩连续重复出现的字符 比如字符串 abcbc 由于无连续重复字符 压缩后的字符串还是 abcbc 2 压缩字段的格式为 字符重复的次数 字符 例如 字符串 xxxyyyyyyz 压缩后就成为 3x6yz
字符串压缩
#include
#include
const int N=100 ; using namespace std ; void stringZip(const char *pInputStr, long InputLen, char *pOutputStr); int main() { char input[N]; char *output=new char [strlen (input)+1 ]; cin .getline(input,N); stringZip(input,strlen (input),output); cout <
delete output;
return
0 ; }
void stringZip(
const
char *pInputStr,
long InputLen,
char *pOutputStr) {
const
char *p=pInputStr;
int i=
0 ,j,num=
1 ; p++;
while (*p!=NULL)
{
while (*p==*(p-
1 ) && *p!=NULL)
{ num++; p++; }
if (num>
1 ) {
int size=
0 ;
int temp; temp=num;
while (num)
{ size++; num/=
10 ; }
for (j=size;j>
0 ;j--)
{ pOutputStr[i+j-
1 ]=temp%
10 +
'0' ; temp/=
10 ; } i+=size;
pOutputStr[i++]=*(p-
1 ); p++; num=
1 ; }
else { pOutputStr[i++]=*(p-
1 ); p++; } } pOutputStr[i++]=*(p-
1 ); pOutputStr[i]=
'\0' ; }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/219300.html 原文链接:https://javaforall.net