算法-字符串压缩

今天做了一道字符串压缩的算法题,原题的输入字符串长度都固定了,突然想到如果输入不固定,也就是不知道要输入的字符串长度的话,那应该怎么做呢?C++中STL里的vector是个不错的选择。
通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1. 仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc".
2. 压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"

要求实现函数: 
void stringZip(const vector<char> &pInputStr, long lInputLen, vector<char> &pOutputStr);

【输入】 pInputStr:  输入字符串
         lInputLen:  输入字符串长度         
【输出】 pOutputStr: 输出字符串;

示例 
输入:“cccddecc”   输出:“3c2de2c”
输入:“adef”     输出:“adef”
输入:“pppppppp” 输出:“8p”
代码:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
void stringZip(const vector<char> &pInputStr, long lInputLen, vector<char> &OutputStr);

int main()
{
	vector<char> InStr;  
	vector<char> OutStr;
	string tempStr;
	while(cin>>tempStr)
        {
	    const char *p = tempStr.data();
	    long n = tempStr.length();
	    for(int i=0; i<n; i++)
	    {
		    InStr.push_back(p[i]);
	    }
	    stringZip(InStr,n,OutStr);
            for(vector<char>::iterator it=OutStr.begin(); it!=OutStr.end(); it++)
	    {
		    cout<<*it;
	    }
		cout<<endl;
		InStr.clear();
		OutStr.clear();
	}
	system("pause");
	return 0;
}

void stringZip(const vector<char> &pInputStr, long lInputLen, vector<char> &pOutputStr)
{
	const vector<char> pTemp = pInputStr;
	long n = lInputLen;
	char buffer[30];
	int a[128] = {0};
	char result[100];//用于存方出现的字符,不重复
	int k=0;
	if(pTemp.empty() || n < 0)
		return;
	for(int i=0; i<n; i++)
	{		
		if(a[pTemp[i]] == 0)
		{
			result[k++] = pTemp[i];
			//pOutputStr[j++]
		}
		a[pTemp[i]]++;
	}
	int j=0;
	for(int i=0; i<k; i++)
	{
            if(a[result[i]] ==1)
	    {
	         pOutputStr.push_back(result[i]);
	    }
	   else
	   {
		memset(buffer, 0, sizeof(buffer));  
                itoa(a[result[i]], buffer, 10); //将字符出现个数int转化为string或char*
		for(int m=0; buffer[m]!='\0'; m++)   //逐个压入容器
                     pOutputStr.push_back(buffer[m]);
		pOutputStr.push_back(result[i]);    //最后压入字符
	   }
	}
}
刚写完的时候,有个地方很容易忽略,就是字符出现的个数是有可能大于9个的。之前int转字符我简单的用了char pStr[i] = '0'+a[i],这种用法在个数不超过9的时候可以使用,但大于等于10个的时候就会出问题了,比如‘0’+11=‘b’。总的来说C++中的vector容器作为动态数组来说还是非常好用的,以后要熟练使用才是。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值