您的位置:首页 > 其它

华为笔试

2015-07-01 23:14 267 查看
通过键盘输入一串小写字母(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”

#include "stdafx.h"

#include<iostream>

using namespace std;

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);

int _tmain(int argc, _TCHAR* argv[])

{

char*in = "aaaabcccff";

int len = strlen(in) + 1;

char*out = new char[2*len];

for (int i = 0; i < 2 * len; i++)

out[i] = ' ';

stringZip(in, len, out);

for (int i = 0; i < 2 * len; i++)

cout <<out[i];

cout << endl;

cout << len << endl;

system("pause");

return 0;

}

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)

{

for (int i = 0,m=0; i < lInputLen-1; )

{

int k = 1;

while (pInputStr[i]==pInputStr[i+1])

{

i = i + 1;

k = k + 1;

}

//char* aa;

//_itoa(k, aa, 10);

//int ff = strlen(aa);

//for (int i = 0; i < ff; i++)

//pOutputStr[m + i] = aa[i];

//pOutputStr[m + ff] = pInputStr[i];

pOutputStr[m] =k+'0';

pOutputStr[m + 1] = pInputStr[i];

i = i + 1;

//m = m + ff+1;

m = m + 2;

}

}

以上解法其实有问题,忽略了连续字符的个数可能超过10个,这时k就不是1位数了。

改进之后如下,思路应该正确,却又出现奇怪的问题,数字后面多了一个a,这个a是从哪里冒出来的?

#include "stdafx.h"

#include<iostream>

using namespace std;

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);

int _tmain(int argc, _TCHAR* argv[])

{

char*in = "aaaaaaaaaaaabcccff";

int len = strlen(in) + 1;

char*out = new char[2 * len];

for (int i = 0; i < 2 * len; i++)

out[i] = ' ';

stringZip(in, len, out);

for (int i = 0; i < 2 * len; i++)

cout << out[i];

cout << endl;

cout << len << endl;

char* bb = new char[10];

for (int i = 0; i < 10; i++)

bb[i] = ' ';

_itoa(30, bb, 10);

for (int i = 0; i < 10; i++)

cout<<bb[i];

system("pause");

return 0;

}

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)

{

for (int i = 0, m = 0; i < lInputLen - 1;)

{

int k = 1;

while (pInputStr[i] == pInputStr[i + 1])

{

i = i + 1;

k = k + 1;

}

char* aa = new char[10];

for (int i = 0; i < 10; i++)

aa[i] = ' ';

_itoa(k, aa, 10);

int dd = 0;

for (int i = 0; i < 10; i++)

{

if (aa[i] == ' ')

break;

pOutputStr[m + i] = aa[i];

dd = dd + 1;

}

pOutputStr[m + dd] = pInputStr[i];

i = i + 1;

m = m + dd + 1;

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: