【练习题】proj2 字符串压缩

输入一个字符串,输出简单的压缩

1)单字符串压缩 :
输入:ABBBCCD , 输出AB3C2D
2)多字符串压缩
输入:AABCABCD,输出A(ABC)2D
1)压缩单个字符
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
string func(string data){
    int pre = data[0];
    for(int i=1;i<(int)data.size();i++){
        cout << "find:"<<data[i]<<endl;
        char temp = data[i];
        if(temp == pre){
            int pos = i;
            data[pos]='2';
            cout << "same"<<endl;
            temp = data[++i];
            while(temp == pre){
                data[pos]++;
                temp = data[(++i)];
            }
            i=pos;
            data.erase(pos+1,(data[pos]-'0')-2);
        }
        pre = data[i];
    }
    return data;
}
int main(){
    string result;

    string s="xxxxxxxyyyyyyz";
    result = func(s);
    cout << result <<endl;
    return 0;
}

转一个别人的做法感觉比我的做法好

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr){
    // 安全检查
    assert((pInputStr != NULL) && (pOutputStr != NULL));
    char mark = *pInputStr;
    int count = 0;
    long j = 0; // 压缩之后的str的下标
    for (long i = 0; i <= lInputLen; i ++){
        // 判断是否一样
        if (i < lInputLen && mark == pInputStr[i]){
            count++;
        }
        else
        {
            if (count > 1){
                //zip str
                pOutputStr[j] = count;
                pOutputStr[++j] = mark;
                j ++;
                count = 1;
            }
            else // if (count == 1){
                pOutputStr[j] = mark;
                j++;
            }
            mark = pInputStr[i];
            }
    }
}

 

2)压缩字符串

第二个没啥思路啊

#include <iostream>#include <vector>#include <algorithm>#include <string>using namespace std;//1 2 3 4 5 1000 2//一个字符串,找最长无重复字母子串.string func(string data){    int pre = data[0];    for(int i=1;i<(int)data.size();i++){        cout << "find:"<<data[i]<<endl;        char temp = data[i];        if(temp == pre){            int pos = i;            data[pos]='2';            cout << "same"<<endl;            temp = data[++i];            while(temp == pre){                data[pos]++;                temp = data[(++i)];            }            i=pos;            data.erase(pos+1,(data[pos]-'0')-2);        }        pre = data[i];    }    return data;}int main(){    string result;
    string s="xxxxxxxyyyyyyz";    result = func(s);    //result.erase(2);    cout << result <<endl;    return 0;}

转载于:https://www.cnblogs.com/ray5wang/p/9574385.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值